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 "CheckExprLifetime.h"
14 #include "TreeTransform.h"
15 #include "UsedDeclVisitor.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/ASTMutationListener.h"
20 #include "clang/AST/CXXInheritance.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/DynamicRecursiveASTVisitor.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/ExprObjC.h"
29 #include "clang/AST/MangleNumberingContext.h"
30 #include "clang/AST/OperationKinds.h"
31 #include "clang/AST/Type.h"
32 #include "clang/AST/TypeLoc.h"
33 #include "clang/Basic/Builtins.h"
34 #include "clang/Basic/DiagnosticSema.h"
35 #include "clang/Basic/PartialDiagnostic.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Basic/Specifiers.h"
38 #include "clang/Basic/TargetInfo.h"
39 #include "clang/Basic/TypeTraits.h"
40 #include "clang/Lex/LiteralSupport.h"
41 #include "clang/Lex/Preprocessor.h"
42 #include "clang/Sema/AnalysisBasedWarnings.h"
43 #include "clang/Sema/DeclSpec.h"
44 #include "clang/Sema/DelayedDiagnostic.h"
45 #include "clang/Sema/Designator.h"
46 #include "clang/Sema/EnterExpressionEvaluationContext.h"
47 #include "clang/Sema/Initialization.h"
48 #include "clang/Sema/Lookup.h"
49 #include "clang/Sema/Overload.h"
50 #include "clang/Sema/ParsedTemplate.h"
51 #include "clang/Sema/Scope.h"
52 #include "clang/Sema/ScopeInfo.h"
53 #include "clang/Sema/SemaCUDA.h"
54 #include "clang/Sema/SemaFixItUtils.h"
55 #include "clang/Sema/SemaHLSL.h"
56 #include "clang/Sema/SemaInternal.h"
57 #include "clang/Sema/SemaObjC.h"
58 #include "clang/Sema/SemaOpenMP.h"
59 #include "clang/Sema/SemaPseudoObject.h"
60 #include "clang/Sema/Template.h"
61 #include "llvm/ADT/STLExtras.h"
62 #include "llvm/ADT/STLForwardCompat.h"
63 #include "llvm/ADT/StringExtras.h"
64 #include "llvm/Support/ConvertUTF.h"
65 #include "llvm/Support/SaveAndRestore.h"
66 #include "llvm/Support/TimeProfiler.h"
67 #include "llvm/Support/TypeSize.h"
70 using namespace clang
;
73 bool Sema::CanUseDecl(NamedDecl
*D
, bool TreatUnavailableAsInvalid
) {
74 // See if this is an auto-typed variable whose initializer we are parsing.
75 if (ParsingInitForAutoVars
.count(D
))
78 // See if this is a deleted function.
79 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
83 // If the function has a deduced return type, and we can't deduce it,
84 // then we can't use it either.
85 if (getLangOpts().CPlusPlus14
&& FD
->getReturnType()->isUndeducedType() &&
86 DeduceReturnType(FD
, SourceLocation(), /*Diagnose*/ false))
89 // See if this is an aligned allocation/deallocation function that is
91 if (TreatUnavailableAsInvalid
&&
92 isUnavailableAlignedAllocationFunction(*FD
))
96 // See if this function is unavailable.
97 if (TreatUnavailableAsInvalid
&& D
->getAvailability() == AR_Unavailable
&&
98 cast
<Decl
>(CurContext
)->getAvailability() != AR_Unavailable
)
101 if (isa
<UnresolvedUsingIfExistsDecl
>(D
))
107 static void DiagnoseUnusedOfDecl(Sema
&S
, NamedDecl
*D
, SourceLocation Loc
) {
108 // Warn if this is used but marked unused.
109 if (const auto *A
= D
->getAttr
<UnusedAttr
>()) {
110 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
111 // should diagnose them.
112 if (A
->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused
&&
113 A
->getSemanticSpelling() != UnusedAttr::C23_maybe_unused
) {
114 const Decl
*DC
= cast_or_null
<Decl
>(S
.ObjC().getCurObjCLexicalContext());
115 if (DC
&& !DC
->hasAttr
<UnusedAttr
>())
116 S
.Diag(Loc
, diag::warn_used_but_marked_unused
) << D
;
121 void Sema::NoteDeletedFunction(FunctionDecl
*Decl
) {
122 assert(Decl
&& Decl
->isDeleted());
124 if (Decl
->isDefaulted()) {
125 // If the method was explicitly defaulted, point at that declaration.
126 if (!Decl
->isImplicit())
127 Diag(Decl
->getLocation(), diag::note_implicitly_deleted
);
129 // Try to diagnose why this special member function was implicitly
130 // deleted. This might fail, if that reason no longer applies.
131 DiagnoseDeletedDefaultedFunction(Decl
);
135 auto *Ctor
= dyn_cast
<CXXConstructorDecl
>(Decl
);
136 if (Ctor
&& Ctor
->isInheritingConstructor())
137 return NoteDeletedInheritingConstructor(Ctor
);
139 Diag(Decl
->getLocation(), diag::note_availability_specified_here
)
143 /// Determine whether a FunctionDecl was ever declared with an
144 /// explicit storage class.
145 static bool hasAnyExplicitStorageClass(const FunctionDecl
*D
) {
146 for (auto *I
: D
->redecls()) {
147 if (I
->getStorageClass() != SC_None
)
153 /// Check whether we're in an extern inline function and referring to a
154 /// variable or function with internal linkage (C11 6.7.4p3).
156 /// This is only a warning because we used to silently accept this code, but
157 /// in many cases it will not behave correctly. This is not enabled in C++ mode
158 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
159 /// and so while there may still be user mistakes, most of the time we can't
160 /// prove that there are errors.
161 static void diagnoseUseOfInternalDeclInInlineFunction(Sema
&S
,
163 SourceLocation Loc
) {
164 // This is disabled under C++; there are too many ways for this to fire in
165 // contexts where the warning is a false positive, or where it is technically
166 // correct but benign.
167 if (S
.getLangOpts().CPlusPlus
)
170 // Check if this is an inlined function or method.
171 FunctionDecl
*Current
= S
.getCurFunctionDecl();
174 if (!Current
->isInlined())
176 if (!Current
->isExternallyVisible())
179 // Check if the decl has internal linkage.
180 if (D
->getFormalLinkage() != Linkage::Internal
)
183 // Downgrade from ExtWarn to Extension if
184 // (1) the supposedly external inline function is in the main file,
185 // and probably won't be included anywhere else.
186 // (2) the thing we're referencing is a pure function.
187 // (3) the thing we're referencing is another inline function.
188 // This last can give us false negatives, but it's better than warning on
189 // wrappers for simple C library functions.
190 const FunctionDecl
*UsedFn
= dyn_cast
<FunctionDecl
>(D
);
191 bool DowngradeWarning
= S
.getSourceManager().isInMainFile(Loc
);
192 if (!DowngradeWarning
&& UsedFn
)
193 DowngradeWarning
= UsedFn
->isInlined() || UsedFn
->hasAttr
<ConstAttr
>();
195 S
.Diag(Loc
, DowngradeWarning
? diag::ext_internal_in_extern_inline_quiet
196 : diag::ext_internal_in_extern_inline
)
197 << /*IsVar=*/!UsedFn
<< D
;
199 S
.MaybeSuggestAddingStaticToDecl(Current
);
201 S
.Diag(D
->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at
)
205 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl
*Cur
) {
206 const FunctionDecl
*First
= Cur
->getFirstDecl();
208 // Suggest "static" on the function, if possible.
209 if (!hasAnyExplicitStorageClass(First
)) {
210 SourceLocation DeclBegin
= First
->getSourceRange().getBegin();
211 Diag(DeclBegin
, diag::note_convert_inline_to_static
)
212 << Cur
<< FixItHint::CreateInsertion(DeclBegin
, "static ");
216 bool Sema::DiagnoseUseOfDecl(NamedDecl
*D
, ArrayRef
<SourceLocation
> Locs
,
217 const ObjCInterfaceDecl
*UnknownObjCClass
,
218 bool ObjCPropertyAccess
,
219 bool AvoidPartialAvailabilityChecks
,
220 ObjCInterfaceDecl
*ClassReceiver
,
221 bool SkipTrailingRequiresClause
) {
222 SourceLocation Loc
= Locs
.front();
223 if (getLangOpts().CPlusPlus
&& isa
<FunctionDecl
>(D
)) {
224 // If there were any diagnostics suppressed by template argument deduction,
226 auto Pos
= SuppressedDiagnostics
.find(D
->getCanonicalDecl());
227 if (Pos
!= SuppressedDiagnostics
.end()) {
228 for (const PartialDiagnosticAt
&Suppressed
: Pos
->second
)
229 Diag(Suppressed
.first
, Suppressed
.second
);
231 // Clear out the list of suppressed diagnostics, so that we don't emit
232 // them again for this specialization. However, we don't obsolete this
233 // entry from the table, because we want to avoid ever emitting these
234 // diagnostics again.
238 // C++ [basic.start.main]p3:
239 // The function 'main' shall not be used within a program.
240 if (cast
<FunctionDecl
>(D
)->isMain())
241 Diag(Loc
, diag::ext_main_used
);
243 diagnoseUnavailableAlignedAllocation(*cast
<FunctionDecl
>(D
), Loc
);
246 // See if this is an auto-typed variable whose initializer we are parsing.
247 if (ParsingInitForAutoVars
.count(D
)) {
248 if (isa
<BindingDecl
>(D
)) {
249 Diag(Loc
, diag::err_binding_cannot_appear_in_own_initializer
)
252 Diag(Loc
, diag::err_auto_variable_cannot_appear_in_own_initializer
)
253 << D
->getDeclName() << cast
<VarDecl
>(D
)->getType();
258 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
259 // See if this is a deleted function.
260 if (FD
->isDeleted()) {
261 auto *Ctor
= dyn_cast
<CXXConstructorDecl
>(FD
);
262 if (Ctor
&& Ctor
->isInheritingConstructor())
263 Diag(Loc
, diag::err_deleted_inherited_ctor_use
)
265 << Ctor
->getInheritedConstructor().getConstructor()->getParent();
267 StringLiteral
*Msg
= FD
->getDeletedMessage();
268 Diag(Loc
, diag::err_deleted_function_use
)
269 << (Msg
!= nullptr) << (Msg
? Msg
->getString() : StringRef());
271 NoteDeletedFunction(FD
);
276 // A program that refers explicitly or implicitly to a function with a
277 // trailing requires-clause whose constraint-expression is not satisfied,
278 // other than to declare it, is ill-formed. [...]
280 // See if this is a function with constraints that need to be satisfied.
281 // Check this before deducing the return type, as it might instantiate the
283 if (!SkipTrailingRequiresClause
&& FD
->getTrailingRequiresClause()) {
284 ConstraintSatisfaction Satisfaction
;
285 if (CheckFunctionConstraints(FD
, Satisfaction
, Loc
,
286 /*ForOverloadResolution*/ true))
287 // A diagnostic will have already been generated (non-constant
288 // constraint expression, for example)
290 if (!Satisfaction
.IsSatisfied
) {
292 diag::err_reference_to_function_with_unsatisfied_constraints
)
294 DiagnoseUnsatisfiedConstraint(Satisfaction
);
299 // If the function has a deduced return type, and we can't deduce it,
300 // then we can't use it either.
301 if (getLangOpts().CPlusPlus14
&& FD
->getReturnType()->isUndeducedType() &&
302 DeduceReturnType(FD
, Loc
))
305 if (getLangOpts().CUDA
&& !CUDA().CheckCall(Loc
, FD
))
310 if (auto *Concept
= dyn_cast
<ConceptDecl
>(D
);
311 Concept
&& CheckConceptUseInDefinition(Concept
, Loc
))
314 if (auto *MD
= dyn_cast
<CXXMethodDecl
>(D
)) {
315 // Lambdas are only default-constructible or assignable in C++2a onwards.
316 if (MD
->getParent()->isLambda() &&
317 ((isa
<CXXConstructorDecl
>(MD
) &&
318 cast
<CXXConstructorDecl
>(MD
)->isDefaultConstructor()) ||
319 MD
->isCopyAssignmentOperator() || MD
->isMoveAssignmentOperator())) {
320 Diag(Loc
, diag::warn_cxx17_compat_lambda_def_ctor_assign
)
321 << !isa
<CXXConstructorDecl
>(MD
);
325 auto getReferencedObjCProp
= [](const NamedDecl
*D
) ->
326 const ObjCPropertyDecl
* {
327 if (const auto *MD
= dyn_cast
<ObjCMethodDecl
>(D
))
328 return MD
->findPropertyDecl();
331 if (const ObjCPropertyDecl
*ObjCPDecl
= getReferencedObjCProp(D
)) {
332 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl
, Loc
))
334 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D
, Loc
)) {
338 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
339 // Only the variables omp_in and omp_out are allowed in the combiner.
340 // Only the variables omp_priv and omp_orig are allowed in the
341 // initializer-clause.
342 auto *DRD
= dyn_cast
<OMPDeclareReductionDecl
>(CurContext
);
343 if (LangOpts
.OpenMP
&& DRD
&& !CurContext
->containsDecl(D
) &&
345 Diag(Loc
, diag::err_omp_wrong_var_in_declare_reduction
)
346 << getCurFunction()->HasOMPDeclareReductionCombiner
;
347 Diag(D
->getLocation(), diag::note_entity_declared_at
) << D
;
351 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
352 // List-items in map clauses on this construct may only refer to the declared
353 // variable var and entities that could be referenced by a procedure defined
354 // at the same location.
355 // [OpenMP 5.2] Also allow iterator declared variables.
356 if (LangOpts
.OpenMP
&& isa
<VarDecl
>(D
) &&
357 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(cast
<VarDecl
>(D
))) {
358 Diag(Loc
, diag::err_omp_declare_mapper_wrong_var
)
359 << OpenMP().getOpenMPDeclareMapperVarName();
360 Diag(D
->getLocation(), diag::note_entity_declared_at
) << D
;
364 if (const auto *EmptyD
= dyn_cast
<UnresolvedUsingIfExistsDecl
>(D
)) {
365 Diag(Loc
, diag::err_use_of_empty_using_if_exists
);
366 Diag(EmptyD
->getLocation(), diag::note_empty_using_if_exists_here
);
370 DiagnoseAvailabilityOfDecl(D
, Locs
, UnknownObjCClass
, ObjCPropertyAccess
,
371 AvoidPartialAvailabilityChecks
, ClassReceiver
);
373 DiagnoseUnusedOfDecl(*this, D
, Loc
);
375 diagnoseUseOfInternalDeclInInlineFunction(*this, D
, Loc
);
377 if (D
->hasAttr
<AvailableOnlyInDefaultEvalMethodAttr
>()) {
378 if (getLangOpts().getFPEvalMethod() !=
379 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine
&&
380 PP
.getLastFPEvalPragmaLocation().isValid() &&
381 PP
.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
382 Diag(D
->getLocation(),
383 diag::err_type_available_only_in_default_eval_method
)
387 if (auto *VD
= dyn_cast
<ValueDecl
>(D
))
388 checkTypeSupport(VD
->getType(), Loc
, VD
);
390 if (LangOpts
.SYCLIsDevice
||
391 (LangOpts
.OpenMP
&& LangOpts
.OpenMPIsTargetDevice
)) {
392 if (!Context
.getTargetInfo().isTLSSupported())
393 if (const auto *VD
= dyn_cast
<VarDecl
>(D
))
394 if (VD
->getTLSKind() != VarDecl::TLS_None
)
395 targetDiag(*Locs
.begin(), diag::err_thread_unsupported
);
398 if (isa
<ParmVarDecl
>(D
) && isa
<RequiresExprBodyDecl
>(D
->getDeclContext()) &&
399 !isUnevaluatedContext()) {
400 // C++ [expr.prim.req.nested] p3
401 // A local parameter shall only appear as an unevaluated operand
402 // (Clause 8) within the constraint-expression.
403 Diag(Loc
, diag::err_requires_expr_parameter_referenced_in_evaluated_context
)
405 Diag(D
->getLocation(), diag::note_entity_declared_at
) << D
;
412 void Sema::DiagnoseSentinelCalls(const NamedDecl
*D
, SourceLocation Loc
,
413 ArrayRef
<Expr
*> Args
) {
414 const SentinelAttr
*Attr
= D
->getAttr
<SentinelAttr
>();
418 // The number of formal parameters of the declaration.
419 unsigned NumFormalParams
;
421 // The kind of declaration. This is also an index into a %select in
423 enum { CK_Function
, CK_Method
, CK_Block
} CalleeKind
;
425 if (const auto *MD
= dyn_cast
<ObjCMethodDecl
>(D
)) {
426 NumFormalParams
= MD
->param_size();
427 CalleeKind
= CK_Method
;
428 } else if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
429 NumFormalParams
= FD
->param_size();
430 CalleeKind
= CK_Function
;
431 } else if (const auto *VD
= dyn_cast
<VarDecl
>(D
)) {
432 QualType Ty
= VD
->getType();
433 const FunctionType
*Fn
= nullptr;
434 if (const auto *PtrTy
= Ty
->getAs
<PointerType
>()) {
435 Fn
= PtrTy
->getPointeeType()->getAs
<FunctionType
>();
438 CalleeKind
= CK_Function
;
439 } else if (const auto *PtrTy
= Ty
->getAs
<BlockPointerType
>()) {
440 Fn
= PtrTy
->getPointeeType()->castAs
<FunctionType
>();
441 CalleeKind
= CK_Block
;
446 if (const auto *proto
= dyn_cast
<FunctionProtoType
>(Fn
))
447 NumFormalParams
= proto
->getNumParams();
454 // "NullPos" is the number of formal parameters at the end which
455 // effectively count as part of the variadic arguments. This is
456 // useful if you would prefer to not have *any* formal parameters,
457 // but the language forces you to have at least one.
458 unsigned NullPos
= Attr
->getNullPos();
459 assert((NullPos
== 0 || NullPos
== 1) && "invalid null position on sentinel");
460 NumFormalParams
= (NullPos
> NumFormalParams
? 0 : NumFormalParams
- NullPos
);
462 // The number of arguments which should follow the sentinel.
463 unsigned NumArgsAfterSentinel
= Attr
->getSentinel();
465 // If there aren't enough arguments for all the formal parameters,
466 // the sentinel, and the args after the sentinel, complain.
467 if (Args
.size() < NumFormalParams
+ NumArgsAfterSentinel
+ 1) {
468 Diag(Loc
, diag::warn_not_enough_argument
) << D
->getDeclName();
469 Diag(D
->getLocation(), diag::note_sentinel_here
) << int(CalleeKind
);
473 // Otherwise, find the sentinel expression.
474 const Expr
*SentinelExpr
= Args
[Args
.size() - NumArgsAfterSentinel
- 1];
477 if (SentinelExpr
->isValueDependent())
479 if (Context
.isSentinelNullExpr(SentinelExpr
))
482 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
483 // or 'NULL' if those are actually defined in the context. Only use
484 // 'nil' for ObjC methods, where it's much more likely that the
485 // variadic arguments form a list of object pointers.
486 SourceLocation MissingNilLoc
= getLocForEndOfToken(SentinelExpr
->getEndLoc());
487 std::string NullValue
;
488 if (CalleeKind
== CK_Method
&& PP
.isMacroDefined("nil"))
490 else if (getLangOpts().CPlusPlus11
)
491 NullValue
= "nullptr";
492 else if (PP
.isMacroDefined("NULL"))
495 NullValue
= "(void*) 0";
497 if (MissingNilLoc
.isInvalid())
498 Diag(Loc
, diag::warn_missing_sentinel
) << int(CalleeKind
);
500 Diag(MissingNilLoc
, diag::warn_missing_sentinel
)
502 << FixItHint::CreateInsertion(MissingNilLoc
, ", " + NullValue
);
503 Diag(D
->getLocation(), diag::note_sentinel_here
)
504 << int(CalleeKind
) << Attr
->getRange();
507 SourceRange
Sema::getExprRange(Expr
*E
) const {
508 return E
? E
->getSourceRange() : SourceRange();
511 //===----------------------------------------------------------------------===//
512 // Standard Promotions and Conversions
513 //===----------------------------------------------------------------------===//
515 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
516 ExprResult
Sema::DefaultFunctionArrayConversion(Expr
*E
, bool Diagnose
) {
517 // Handle any placeholder expressions which made it here.
518 if (E
->hasPlaceholderType()) {
519 ExprResult result
= CheckPlaceholderExpr(E
);
520 if (result
.isInvalid()) return ExprError();
524 QualType Ty
= E
->getType();
525 assert(!Ty
.isNull() && "DefaultFunctionArrayConversion - missing type");
527 if (Ty
->isFunctionType()) {
528 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(E
->IgnoreParenCasts()))
529 if (auto *FD
= dyn_cast
<FunctionDecl
>(DRE
->getDecl()))
530 if (!checkAddressOfFunctionIsAvailable(FD
, Diagnose
, E
->getExprLoc()))
533 E
= ImpCastExprToType(E
, Context
.getPointerType(Ty
),
534 CK_FunctionToPointerDecay
).get();
535 } else if (Ty
->isArrayType()) {
536 // In C90 mode, arrays only promote to pointers if the array expression is
537 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
538 // type 'array of type' is converted to an expression that has type 'pointer
539 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
540 // that has type 'array of type' ...". The relevant change is "an lvalue"
541 // (C90) to "an expression" (C99).
544 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
545 // T" can be converted to an rvalue of type "pointer to T".
547 if (getLangOpts().C99
|| getLangOpts().CPlusPlus
|| E
->isLValue()) {
548 ExprResult Res
= ImpCastExprToType(E
, Context
.getArrayDecayedType(Ty
),
549 CK_ArrayToPointerDecay
);
558 static void CheckForNullPointerDereference(Sema
&S
, Expr
*E
) {
559 // Check to see if we are dereferencing a null pointer. If so,
560 // and if not volatile-qualified, this is undefined behavior that the
561 // optimizer will delete, so warn about it. People sometimes try to use this
562 // to get a deterministic trap and are surprised by clang's behavior. This
563 // only handles the pattern "*null", which is a very syntactic check.
564 const auto *UO
= dyn_cast
<UnaryOperator
>(E
->IgnoreParenCasts());
565 if (UO
&& UO
->getOpcode() == UO_Deref
&&
566 UO
->getSubExpr()->getType()->isPointerType()) {
568 UO
->getSubExpr()->getType()->getPointeeType().getAddressSpace();
569 if ((!isTargetAddressSpace(AS
) ||
570 (isTargetAddressSpace(AS
) && toTargetAddressSpace(AS
) == 0)) &&
571 UO
->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
572 S
.Context
, Expr::NPC_ValueDependentIsNotNull
) &&
573 !UO
->getType().isVolatileQualified()) {
574 S
.DiagRuntimeBehavior(UO
->getOperatorLoc(), UO
,
575 S
.PDiag(diag::warn_indirection_through_null
)
576 << UO
->getSubExpr()->getSourceRange());
577 S
.DiagRuntimeBehavior(UO
->getOperatorLoc(), UO
,
578 S
.PDiag(diag::note_indirection_through_null
));
583 static void DiagnoseDirectIsaAccess(Sema
&S
, const ObjCIvarRefExpr
*OIRE
,
584 SourceLocation AssignLoc
,
586 const ObjCIvarDecl
*IV
= OIRE
->getDecl();
590 DeclarationName MemberName
= IV
->getDeclName();
591 IdentifierInfo
*Member
= MemberName
.getAsIdentifierInfo();
592 if (!Member
|| !Member
->isStr("isa"))
595 const Expr
*Base
= OIRE
->getBase();
596 QualType BaseType
= Base
->getType();
598 BaseType
= BaseType
->getPointeeType();
599 if (const ObjCObjectType
*OTy
= BaseType
->getAs
<ObjCObjectType
>())
600 if (ObjCInterfaceDecl
*IDecl
= OTy
->getInterface()) {
601 ObjCInterfaceDecl
*ClassDeclared
= nullptr;
602 ObjCIvarDecl
*IV
= IDecl
->lookupInstanceVariable(Member
, ClassDeclared
);
603 if (!ClassDeclared
->getSuperClass()
604 && (*ClassDeclared
->ivar_begin()) == IV
) {
606 NamedDecl
*ObjectSetClass
=
607 S
.LookupSingleName(S
.TUScope
,
608 &S
.Context
.Idents
.get("object_setClass"),
609 SourceLocation(), S
.LookupOrdinaryName
);
610 if (ObjectSetClass
) {
611 SourceLocation RHSLocEnd
= S
.getLocForEndOfToken(RHS
->getEndLoc());
612 S
.Diag(OIRE
->getExprLoc(), diag::warn_objc_isa_assign
)
613 << FixItHint::CreateInsertion(OIRE
->getBeginLoc(),
615 << FixItHint::CreateReplacement(
616 SourceRange(OIRE
->getOpLoc(), AssignLoc
), ",")
617 << FixItHint::CreateInsertion(RHSLocEnd
, ")");
620 S
.Diag(OIRE
->getLocation(), diag::warn_objc_isa_assign
);
622 NamedDecl
*ObjectGetClass
=
623 S
.LookupSingleName(S
.TUScope
,
624 &S
.Context
.Idents
.get("object_getClass"),
625 SourceLocation(), S
.LookupOrdinaryName
);
627 S
.Diag(OIRE
->getExprLoc(), diag::warn_objc_isa_use
)
628 << FixItHint::CreateInsertion(OIRE
->getBeginLoc(),
630 << FixItHint::CreateReplacement(
631 SourceRange(OIRE
->getOpLoc(), OIRE
->getEndLoc()), ")");
633 S
.Diag(OIRE
->getLocation(), diag::warn_objc_isa_use
);
635 S
.Diag(IV
->getLocation(), diag::note_ivar_decl
);
640 ExprResult
Sema::DefaultLvalueConversion(Expr
*E
) {
641 // Handle any placeholder expressions which made it here.
642 if (E
->hasPlaceholderType()) {
643 ExprResult result
= CheckPlaceholderExpr(E
);
644 if (result
.isInvalid()) return ExprError();
648 // C++ [conv.lval]p1:
649 // A glvalue of a non-function, non-array type T can be
650 // converted to a prvalue.
651 if (!E
->isGLValue()) return E
;
653 QualType T
= E
->getType();
654 assert(!T
.isNull() && "r-value conversion on typeless expression?");
656 // lvalue-to-rvalue conversion cannot be applied to types that decay to
657 // pointers (i.e. function or array types).
658 if (T
->canDecayToPointerType())
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 if (T
== Context
.OverloadTy
|| T
->isRecordType() ||
665 (T
->isDependentType() && !T
->isAnyPointerType() &&
666 !T
->isMemberPointerType()))
670 // The C standard is actually really unclear on this point, and
671 // DR106 tells us what the result should be but not why. It's
672 // generally best to say that void types just doesn't undergo
673 // lvalue-to-rvalue at all. Note that expressions of unqualified
674 // 'void' type are never l-values, but qualified void can be.
678 // OpenCL usually rejects direct accesses to values of 'half' type.
679 if (getLangOpts().OpenCL
&&
680 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
682 Diag(E
->getExprLoc(), diag::err_opencl_half_load_store
)
687 CheckForNullPointerDereference(*this, E
);
688 if (const ObjCIsaExpr
*OISA
= dyn_cast
<ObjCIsaExpr
>(E
->IgnoreParenCasts())) {
689 NamedDecl
*ObjectGetClass
= LookupSingleName(TUScope
,
690 &Context
.Idents
.get("object_getClass"),
691 SourceLocation(), LookupOrdinaryName
);
693 Diag(E
->getExprLoc(), diag::warn_objc_isa_use
)
694 << FixItHint::CreateInsertion(OISA
->getBeginLoc(), "object_getClass(")
695 << FixItHint::CreateReplacement(
696 SourceRange(OISA
->getOpLoc(), OISA
->getIsaMemberLoc()), ")");
698 Diag(E
->getExprLoc(), diag::warn_objc_isa_use
);
700 else if (const ObjCIvarRefExpr
*OIRE
=
701 dyn_cast
<ObjCIvarRefExpr
>(E
->IgnoreParenCasts()))
702 DiagnoseDirectIsaAccess(*this, OIRE
, SourceLocation(), /* Expr*/nullptr);
704 // C++ [conv.lval]p1:
705 // [...] If T is a non-class type, the type of the prvalue is the
706 // cv-unqualified version of T. Otherwise, the type of the
710 // If the lvalue has qualified type, the value has the unqualified
711 // version of the type of the lvalue; otherwise, the value has the
712 // type of the lvalue.
713 if (T
.hasQualifiers())
714 T
= T
.getUnqualifiedType();
716 // Under the MS ABI, lock down the inheritance model now.
717 if (T
->isMemberPointerType() &&
718 Context
.getTargetInfo().getCXXABI().isMicrosoft())
719 (void)isCompleteType(E
->getExprLoc(), T
);
721 ExprResult Res
= CheckLValueToRValueConversionOperand(E
);
726 // Loading a __weak object implicitly retains the value, so we need a cleanup to
728 if (E
->getType().getObjCLifetime() == Qualifiers::OCL_Weak
)
729 Cleanup
.setExprNeedsCleanups(true);
731 if (E
->getType().isDestructedType() == QualType::DK_nontrivial_c_struct
)
732 Cleanup
.setExprNeedsCleanups(true);
734 // C++ [conv.lval]p3:
735 // If T is cv std::nullptr_t, the result is a null pointer constant.
736 CastKind CK
= T
->isNullPtrType() ? CK_NullToPointer
: CK_LValueToRValue
;
737 Res
= ImplicitCastExpr::Create(Context
, T
, CK
, E
, nullptr, VK_PRValue
,
738 CurFPFeatureOverrides());
741 // ... if the lvalue has atomic type, the value has the non-atomic version
742 // of the type of the lvalue ...
743 if (const AtomicType
*Atomic
= T
->getAs
<AtomicType
>()) {
744 T
= Atomic
->getValueType().getUnqualifiedType();
745 Res
= ImplicitCastExpr::Create(Context
, T
, CK_AtomicToNonAtomic
, Res
.get(),
746 nullptr, VK_PRValue
, FPOptionsOverride());
752 ExprResult
Sema::DefaultFunctionArrayLvalueConversion(Expr
*E
, bool Diagnose
) {
753 ExprResult Res
= DefaultFunctionArrayConversion(E
, Diagnose
);
756 Res
= DefaultLvalueConversion(Res
.get());
762 ExprResult
Sema::CallExprUnaryConversions(Expr
*E
) {
763 QualType Ty
= E
->getType();
765 // Only do implicit cast for a function type, but not for a pointer
767 if (Ty
->isFunctionType()) {
768 Res
= ImpCastExprToType(E
, Context
.getPointerType(Ty
),
769 CK_FunctionToPointerDecay
);
773 Res
= DefaultLvalueConversion(Res
.get());
779 /// UsualUnaryConversions - Performs various conversions that are common to most
780 /// operators (C99 6.3). The conversions of array and function types are
781 /// sometimes suppressed. For example, the array->pointer conversion doesn't
782 /// apply if the array is an argument to the sizeof or address (&) operators.
783 /// In these instances, this routine should *not* be called.
784 ExprResult
Sema::UsualUnaryConversions(Expr
*E
) {
785 // First, convert to an r-value.
786 ExprResult Res
= DefaultFunctionArrayLvalueConversion(E
);
791 QualType Ty
= E
->getType();
792 assert(!Ty
.isNull() && "UsualUnaryConversions - missing type");
794 LangOptions::FPEvalMethodKind EvalMethod
= CurFPFeatures
.getFPEvalMethod();
795 if (EvalMethod
!= LangOptions::FEM_Source
&& Ty
->isFloatingType() &&
796 (getLangOpts().getFPEvalMethod() !=
797 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine
||
798 PP
.getLastFPEvalPragmaLocation().isValid())) {
799 switch (EvalMethod
) {
801 llvm_unreachable("Unrecognized float evaluation method");
803 case LangOptions::FEM_UnsetOnCommandLine
:
804 llvm_unreachable("Float evaluation method should be set by now");
806 case LangOptions::FEM_Double
:
807 if (Context
.getFloatingTypeOrder(Context
.DoubleTy
, Ty
) > 0)
808 // Widen the expression to double.
809 return Ty
->isComplexType()
810 ? ImpCastExprToType(E
,
811 Context
.getComplexType(Context
.DoubleTy
),
812 CK_FloatingComplexCast
)
813 : ImpCastExprToType(E
, Context
.DoubleTy
, CK_FloatingCast
);
815 case LangOptions::FEM_Extended
:
816 if (Context
.getFloatingTypeOrder(Context
.LongDoubleTy
, Ty
) > 0)
817 // Widen the expression to long double.
818 return Ty
->isComplexType()
820 E
, Context
.getComplexType(Context
.LongDoubleTy
),
821 CK_FloatingComplexCast
)
822 : ImpCastExprToType(E
, Context
.LongDoubleTy
,
828 // Half FP have to be promoted to float unless it is natively supported
829 if (Ty
->isHalfType() && !getLangOpts().NativeHalfType
)
830 return ImpCastExprToType(Res
.get(), Context
.FloatTy
, CK_FloatingCast
);
832 // Try to perform integral promotions if the object has a theoretically
834 if (Ty
->isIntegralOrUnscopedEnumerationType()) {
837 // The following may be used in an expression wherever an int or
838 // unsigned int may be used:
839 // - an object or expression with an integer type whose integer
840 // conversion rank is less than or equal to the rank of int
842 // - A bit-field of type _Bool, int, signed int, or unsigned int.
844 // If an int can represent all values of the original type, the
845 // value is converted to an int; otherwise, it is converted to an
846 // unsigned int. These are called the integer promotions. All
847 // other types are unchanged by the integer promotions.
849 QualType PTy
= Context
.isPromotableBitField(E
);
851 E
= ImpCastExprToType(E
, PTy
, CK_IntegralCast
).get();
854 if (Context
.isPromotableIntegerType(Ty
)) {
855 QualType PT
= Context
.getPromotedIntegerType(Ty
);
856 E
= ImpCastExprToType(E
, PT
, CK_IntegralCast
).get();
863 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
864 /// do not have a prototype. Arguments that have type float or __fp16
865 /// are promoted to double. All other argument types are converted by
866 /// UsualUnaryConversions().
867 ExprResult
Sema::DefaultArgumentPromotion(Expr
*E
) {
868 QualType Ty
= E
->getType();
869 assert(!Ty
.isNull() && "DefaultArgumentPromotion - missing type");
871 ExprResult Res
= UsualUnaryConversions(E
);
876 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
877 // promote to double.
878 // Note that default argument promotion applies only to float (and
879 // half/fp16); it does not apply to _Float16.
880 const BuiltinType
*BTy
= Ty
->getAs
<BuiltinType
>();
881 if (BTy
&& (BTy
->getKind() == BuiltinType::Half
||
882 BTy
->getKind() == BuiltinType::Float
)) {
883 if (getLangOpts().OpenCL
&&
884 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
885 if (BTy
->getKind() == BuiltinType::Half
) {
886 E
= ImpCastExprToType(E
, Context
.FloatTy
, CK_FloatingCast
).get();
889 E
= ImpCastExprToType(E
, Context
.DoubleTy
, CK_FloatingCast
).get();
893 getLangOpts().getExtendIntArgs() ==
894 LangOptions::ExtendArgsKind::ExtendTo64
&&
895 Context
.getTargetInfo().supportsExtendIntArgs() && Ty
->isIntegerType() &&
896 Context
.getTypeSizeInChars(BTy
) <
897 Context
.getTypeSizeInChars(Context
.LongLongTy
)) {
898 E
= (Ty
->isUnsignedIntegerType())
899 ? ImpCastExprToType(E
, Context
.UnsignedLongLongTy
, CK_IntegralCast
)
901 : ImpCastExprToType(E
, Context
.LongLongTy
, CK_IntegralCast
).get();
902 assert(8 == Context
.getTypeSizeInChars(Context
.LongLongTy
).getQuantity() &&
903 "Unexpected typesize for LongLongTy");
906 // C++ performs lvalue-to-rvalue conversion as a default argument
907 // promotion, even on class types, but note:
908 // C++11 [conv.lval]p2:
909 // When an lvalue-to-rvalue conversion occurs in an unevaluated
910 // operand or a subexpression thereof the value contained in the
911 // referenced object is not accessed. Otherwise, if the glvalue
912 // has a class type, the conversion copy-initializes a temporary
913 // of type T from the glvalue and the result of the conversion
914 // is a prvalue for the temporary.
915 // FIXME: add some way to gate this entire thing for correctness in
916 // potentially potentially evaluated contexts.
917 if (getLangOpts().CPlusPlus
&& E
->isGLValue() && !isUnevaluatedContext()) {
918 ExprResult Temp
= PerformCopyInitialization(
919 InitializedEntity::InitializeTemporary(E
->getType()),
921 if (Temp
.isInvalid())
926 // C++ [expr.call]p7, per CWG722:
927 // An argument that has (possibly cv-qualified) type std::nullptr_t is
928 // converted to void* ([conv.ptr]).
929 // (This does not apply to C23 nullptr)
930 if (getLangOpts().CPlusPlus
&& E
->getType()->isNullPtrType())
931 E
= ImpCastExprToType(E
, Context
.VoidPtrTy
, CK_NullToPointer
).get();
936 Sema::VarArgKind
Sema::isValidVarArgType(const QualType
&Ty
) {
937 if (Ty
->isIncompleteType()) {
938 // C++11 [expr.call]p7:
939 // After these conversions, if the argument does not have arithmetic,
940 // enumeration, pointer, pointer to member, or class type, the program
943 // Since we've already performed null pointer conversion, array-to-pointer
944 // decay and function-to-pointer decay, the only such type in C++ is cv
945 // void. This also handles initializer lists as variadic arguments.
946 if (Ty
->isVoidType())
949 if (Ty
->isObjCObjectType())
954 if (Ty
.isDestructedType() == QualType::DK_nontrivial_c_struct
)
957 if (Context
.getTargetInfo().getTriple().isWasm() &&
958 Ty
.isWebAssemblyReferenceType()) {
962 if (Ty
.isCXX98PODType(Context
))
965 // C++11 [expr.call]p7:
966 // Passing a potentially-evaluated argument of class type (Clause 9)
967 // having a non-trivial copy constructor, a non-trivial move constructor,
968 // or a non-trivial destructor, with no corresponding parameter,
969 // is conditionally-supported with implementation-defined semantics.
970 if (getLangOpts().CPlusPlus11
&& !Ty
->isDependentType())
971 if (CXXRecordDecl
*Record
= Ty
->getAsCXXRecordDecl())
972 if (!Record
->hasNonTrivialCopyConstructor() &&
973 !Record
->hasNonTrivialMoveConstructor() &&
974 !Record
->hasNonTrivialDestructor())
975 return VAK_ValidInCXX11
;
977 if (getLangOpts().ObjCAutoRefCount
&& Ty
->isObjCLifetimeType())
980 if (Ty
->isObjCObjectType())
983 if (getLangOpts().MSVCCompat
)
984 return VAK_MSVCUndefined
;
986 if (getLangOpts().HLSL
&& Ty
->getAs
<HLSLAttributedResourceType
>())
989 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
990 // permitted to reject them. We should consider doing so.
991 return VAK_Undefined
;
994 void Sema::checkVariadicArgument(const Expr
*E
, VariadicCallType CT
) {
995 // Don't allow one to pass an Objective-C interface to a vararg.
996 const QualType
&Ty
= E
->getType();
997 VarArgKind VAK
= isValidVarArgType(Ty
);
999 // Complain about passing non-POD types through varargs.
1001 case VAK_ValidInCXX11
:
1002 DiagRuntimeBehavior(
1003 E
->getBeginLoc(), nullptr,
1004 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg
) << Ty
<< CT
);
1007 if (Ty
->isRecordType()) {
1008 // This is unlikely to be what the user intended. If the class has a
1009 // 'c_str' member function, the user probably meant to call that.
1010 DiagRuntimeBehavior(E
->getBeginLoc(), nullptr,
1011 PDiag(diag::warn_pass_class_arg_to_vararg
)
1012 << Ty
<< CT
<< hasCStrMethod(E
) << ".c_str()");
1017 case VAK_MSVCUndefined
:
1018 DiagRuntimeBehavior(E
->getBeginLoc(), nullptr,
1019 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg
)
1020 << getLangOpts().CPlusPlus11
<< Ty
<< CT
);
1024 if (Ty
.isDestructedType() == QualType::DK_nontrivial_c_struct
)
1025 Diag(E
->getBeginLoc(),
1026 diag::err_cannot_pass_non_trivial_c_struct_to_vararg
)
1028 else if (Ty
->isObjCObjectType())
1029 DiagRuntimeBehavior(E
->getBeginLoc(), nullptr,
1030 PDiag(diag::err_cannot_pass_objc_interface_to_vararg
)
1033 Diag(E
->getBeginLoc(), diag::err_cannot_pass_to_vararg
)
1034 << isa
<InitListExpr
>(E
) << Ty
<< CT
;
1039 ExprResult
Sema::DefaultVariadicArgumentPromotion(Expr
*E
, VariadicCallType CT
,
1040 FunctionDecl
*FDecl
) {
1041 if (const BuiltinType
*PlaceholderTy
= E
->getType()->getAsPlaceholderType()) {
1042 // Strip the unbridged-cast placeholder expression off, if applicable.
1043 if (PlaceholderTy
->getKind() == BuiltinType::ARCUnbridgedCast
&&
1044 (CT
== VariadicMethod
||
1045 (FDecl
&& FDecl
->hasAttr
<CFAuditedTransferAttr
>()))) {
1046 E
= ObjC().stripARCUnbridgedCast(E
);
1048 // Otherwise, do normal placeholder checking.
1050 ExprResult ExprRes
= CheckPlaceholderExpr(E
);
1051 if (ExprRes
.isInvalid())
1057 ExprResult ExprRes
= DefaultArgumentPromotion(E
);
1058 if (ExprRes
.isInvalid())
1061 // Copy blocks to the heap.
1062 if (ExprRes
.get()->getType()->isBlockPointerType())
1063 maybeExtendBlockObject(ExprRes
);
1067 // Diagnostics regarding non-POD argument types are
1068 // emitted along with format string checking in Sema::CheckFunctionCall().
1069 if (isValidVarArgType(E
->getType()) == VAK_Undefined
) {
1070 // Turn this into a trap.
1072 SourceLocation TemplateKWLoc
;
1074 Name
.setIdentifier(PP
.getIdentifierInfo("__builtin_trap"),
1076 ExprResult TrapFn
= ActOnIdExpression(TUScope
, SS
, TemplateKWLoc
, Name
,
1077 /*HasTrailingLParen=*/true,
1078 /*IsAddressOfOperand=*/false);
1079 if (TrapFn
.isInvalid())
1082 ExprResult Call
= BuildCallExpr(TUScope
, TrapFn
.get(), E
->getBeginLoc(), {},
1084 if (Call
.isInvalid())
1088 ActOnBinOp(TUScope
, E
->getBeginLoc(), tok::comma
, Call
.get(), E
);
1089 if (Comma
.isInvalid())
1094 if (!getLangOpts().CPlusPlus
&&
1095 RequireCompleteType(E
->getExprLoc(), E
->getType(),
1096 diag::err_call_incomplete_argument
))
1102 /// Convert complex integers to complex floats and real integers to
1103 /// real floats as required for complex arithmetic. Helper function of
1104 /// UsualArithmeticConversions()
1106 /// \return false if the integer expression is an integer type and is
1107 /// successfully converted to the (complex) float type.
1108 static bool handleComplexIntegerToFloatConversion(Sema
&S
, ExprResult
&IntExpr
,
1109 ExprResult
&ComplexExpr
,
1113 if (IntTy
->isComplexType() || IntTy
->isRealFloatingType()) return true;
1114 if (SkipCast
) return false;
1115 if (IntTy
->isIntegerType()) {
1116 QualType fpTy
= ComplexTy
->castAs
<ComplexType
>()->getElementType();
1117 IntExpr
= S
.ImpCastExprToType(IntExpr
.get(), fpTy
, CK_IntegralToFloating
);
1119 assert(IntTy
->isComplexIntegerType());
1120 IntExpr
= S
.ImpCastExprToType(IntExpr
.get(), ComplexTy
,
1121 CK_IntegralComplexToFloatingComplex
);
1126 // This handles complex/complex, complex/float, or float/complex.
1127 // When both operands are complex, the shorter operand is converted to the
1128 // type of the longer, and that is the type of the result. This corresponds
1129 // to what is done when combining two real floating-point operands.
1130 // The fun begins when size promotion occur across type domains.
1131 // From H&S 6.3.4: When one operand is complex and the other is a real
1132 // floating-point type, the less precise type is converted, within it's
1133 // real or complex domain, to the precision of the other type. For example,
1134 // when combining a "long double" with a "double _Complex", the
1135 // "double _Complex" is promoted to "long double _Complex".
1136 static QualType
handleComplexFloatConversion(Sema
&S
, ExprResult
&Shorter
,
1137 QualType ShorterType
,
1138 QualType LongerType
,
1139 bool PromotePrecision
) {
1140 bool LongerIsComplex
= isa
<ComplexType
>(LongerType
.getCanonicalType());
1142 LongerIsComplex
? LongerType
: S
.Context
.getComplexType(LongerType
);
1144 if (PromotePrecision
) {
1145 if (isa
<ComplexType
>(ShorterType
.getCanonicalType())) {
1147 S
.ImpCastExprToType(Shorter
.get(), Result
, CK_FloatingComplexCast
);
1149 if (LongerIsComplex
)
1150 LongerType
= LongerType
->castAs
<ComplexType
>()->getElementType();
1151 Shorter
= S
.ImpCastExprToType(Shorter
.get(), LongerType
, CK_FloatingCast
);
1157 /// Handle arithmetic conversion with complex types. Helper function of
1158 /// UsualArithmeticConversions()
1159 static QualType
handleComplexConversion(Sema
&S
, ExprResult
&LHS
,
1160 ExprResult
&RHS
, QualType LHSType
,
1161 QualType RHSType
, bool IsCompAssign
) {
1162 // Handle (complex) integer types.
1163 if (!handleComplexIntegerToFloatConversion(S
, RHS
, LHS
, RHSType
, LHSType
,
1164 /*SkipCast=*/false))
1166 if (!handleComplexIntegerToFloatConversion(S
, LHS
, RHS
, LHSType
, RHSType
,
1167 /*SkipCast=*/IsCompAssign
))
1170 // Compute the rank of the two types, regardless of whether they are complex.
1171 int Order
= S
.Context
.getFloatingTypeOrder(LHSType
, RHSType
);
1173 // Promote the precision of the LHS if not an assignment.
1174 return handleComplexFloatConversion(S
, LHS
, LHSType
, RHSType
,
1175 /*PromotePrecision=*/!IsCompAssign
);
1176 // Promote the precision of the RHS unless it is already the same as the LHS.
1177 return handleComplexFloatConversion(S
, RHS
, RHSType
, LHSType
,
1178 /*PromotePrecision=*/Order
> 0);
1181 /// Handle arithmetic conversion from integer to float. Helper function
1182 /// of UsualArithmeticConversions()
1183 static QualType
handleIntToFloatConversion(Sema
&S
, ExprResult
&FloatExpr
,
1184 ExprResult
&IntExpr
,
1185 QualType FloatTy
, QualType IntTy
,
1186 bool ConvertFloat
, bool ConvertInt
) {
1187 if (IntTy
->isIntegerType()) {
1189 // Convert intExpr to the lhs floating point type.
1190 IntExpr
= S
.ImpCastExprToType(IntExpr
.get(), FloatTy
,
1191 CK_IntegralToFloating
);
1195 // Convert both sides to the appropriate complex float.
1196 assert(IntTy
->isComplexIntegerType());
1197 QualType result
= S
.Context
.getComplexType(FloatTy
);
1199 // _Complex int -> _Complex float
1201 IntExpr
= S
.ImpCastExprToType(IntExpr
.get(), result
,
1202 CK_IntegralComplexToFloatingComplex
);
1204 // float -> _Complex float
1206 FloatExpr
= S
.ImpCastExprToType(FloatExpr
.get(), result
,
1207 CK_FloatingRealToComplex
);
1212 /// Handle arithmethic conversion with floating point types. Helper
1213 /// function of UsualArithmeticConversions()
1214 static QualType
handleFloatConversion(Sema
&S
, ExprResult
&LHS
,
1215 ExprResult
&RHS
, QualType LHSType
,
1216 QualType RHSType
, bool IsCompAssign
) {
1217 bool LHSFloat
= LHSType
->isRealFloatingType();
1218 bool RHSFloat
= RHSType
->isRealFloatingType();
1220 // N1169 4.1.4: If one of the operands has a floating type and the other
1221 // operand has a fixed-point type, the fixed-point operand
1222 // is converted to the floating type [...]
1223 if (LHSType
->isFixedPointType() || RHSType
->isFixedPointType()) {
1225 RHS
= S
.ImpCastExprToType(RHS
.get(), LHSType
, CK_FixedPointToFloating
);
1226 else if (!IsCompAssign
)
1227 LHS
= S
.ImpCastExprToType(LHS
.get(), RHSType
, CK_FixedPointToFloating
);
1228 return LHSFloat
? LHSType
: RHSType
;
1231 // If we have two real floating types, convert the smaller operand
1232 // to the bigger result.
1233 if (LHSFloat
&& RHSFloat
) {
1234 int order
= S
.Context
.getFloatingTypeOrder(LHSType
, RHSType
);
1236 RHS
= S
.ImpCastExprToType(RHS
.get(), LHSType
, CK_FloatingCast
);
1240 assert(order
< 0 && "illegal float comparison");
1242 LHS
= S
.ImpCastExprToType(LHS
.get(), RHSType
, CK_FloatingCast
);
1247 // Half FP has to be promoted to float unless it is natively supported
1248 if (LHSType
->isHalfType() && !S
.getLangOpts().NativeHalfType
)
1249 LHSType
= S
.Context
.FloatTy
;
1251 return handleIntToFloatConversion(S
, LHS
, RHS
, LHSType
, RHSType
,
1252 /*ConvertFloat=*/!IsCompAssign
,
1253 /*ConvertInt=*/ true);
1256 return handleIntToFloatConversion(S
, RHS
, LHS
, RHSType
, LHSType
,
1257 /*ConvertFloat=*/ true,
1258 /*ConvertInt=*/!IsCompAssign
);
1261 /// Diagnose attempts to convert between __float128, __ibm128 and
1262 /// long double if there is no support for such conversion.
1263 /// Helper function of UsualArithmeticConversions().
1264 static bool unsupportedTypeConversion(const Sema
&S
, QualType LHSType
,
1266 // No issue if either is not a floating point type.
1267 if (!LHSType
->isFloatingType() || !RHSType
->isFloatingType())
1270 // No issue if both have the same 128-bit float semantics.
1271 auto *LHSComplex
= LHSType
->getAs
<ComplexType
>();
1272 auto *RHSComplex
= RHSType
->getAs
<ComplexType
>();
1274 QualType LHSElem
= LHSComplex
? LHSComplex
->getElementType() : LHSType
;
1275 QualType RHSElem
= RHSComplex
? RHSComplex
->getElementType() : RHSType
;
1277 const llvm::fltSemantics
&LHSSem
= S
.Context
.getFloatTypeSemantics(LHSElem
);
1278 const llvm::fltSemantics
&RHSSem
= S
.Context
.getFloatTypeSemantics(RHSElem
);
1280 if ((&LHSSem
!= &llvm::APFloat::PPCDoubleDouble() ||
1281 &RHSSem
!= &llvm::APFloat::IEEEquad()) &&
1282 (&LHSSem
!= &llvm::APFloat::IEEEquad() ||
1283 &RHSSem
!= &llvm::APFloat::PPCDoubleDouble()))
1289 typedef ExprResult
PerformCastFn(Sema
&S
, Expr
*operand
, QualType toType
);
1292 /// These helper callbacks are placed in an anonymous namespace to
1293 /// permit their use as function template parameters.
1294 ExprResult
doIntegralCast(Sema
&S
, Expr
*op
, QualType toType
) {
1295 return S
.ImpCastExprToType(op
, toType
, CK_IntegralCast
);
1298 ExprResult
doComplexIntegralCast(Sema
&S
, Expr
*op
, QualType toType
) {
1299 return S
.ImpCastExprToType(op
, S
.Context
.getComplexType(toType
),
1300 CK_IntegralComplexCast
);
1304 /// Handle integer arithmetic conversions. Helper function of
1305 /// UsualArithmeticConversions()
1306 template <PerformCastFn doLHSCast
, PerformCastFn doRHSCast
>
1307 static QualType
handleIntegerConversion(Sema
&S
, ExprResult
&LHS
,
1308 ExprResult
&RHS
, QualType LHSType
,
1309 QualType RHSType
, bool IsCompAssign
) {
1310 // The rules for this case are in C99 6.3.1.8
1311 int order
= S
.Context
.getIntegerTypeOrder(LHSType
, RHSType
);
1312 bool LHSSigned
= LHSType
->hasSignedIntegerRepresentation();
1313 bool RHSSigned
= RHSType
->hasSignedIntegerRepresentation();
1314 if (LHSSigned
== RHSSigned
) {
1315 // Same signedness; use the higher-ranked type
1317 RHS
= (*doRHSCast
)(S
, RHS
.get(), LHSType
);
1319 } else if (!IsCompAssign
)
1320 LHS
= (*doLHSCast
)(S
, LHS
.get(), RHSType
);
1322 } else if (order
!= (LHSSigned
? 1 : -1)) {
1323 // The unsigned type has greater than or equal rank to the
1324 // signed type, so use the unsigned type
1326 RHS
= (*doRHSCast
)(S
, RHS
.get(), LHSType
);
1328 } else if (!IsCompAssign
)
1329 LHS
= (*doLHSCast
)(S
, LHS
.get(), RHSType
);
1331 } else if (S
.Context
.getIntWidth(LHSType
) != S
.Context
.getIntWidth(RHSType
)) {
1332 // The two types are different widths; if we are here, that
1333 // means the signed type is larger than the unsigned type, so
1334 // use the signed type.
1336 RHS
= (*doRHSCast
)(S
, RHS
.get(), LHSType
);
1338 } else if (!IsCompAssign
)
1339 LHS
= (*doLHSCast
)(S
, LHS
.get(), RHSType
);
1342 // The signed type is higher-ranked than the unsigned type,
1343 // but isn't actually any bigger (like unsigned int and long
1344 // on most 32-bit systems). Use the unsigned type corresponding
1345 // to the signed type.
1347 S
.Context
.getCorrespondingUnsignedType(LHSSigned
? LHSType
: RHSType
);
1348 RHS
= (*doRHSCast
)(S
, RHS
.get(), result
);
1350 LHS
= (*doLHSCast
)(S
, LHS
.get(), result
);
1355 /// Handle conversions with GCC complex int extension. Helper function
1356 /// of UsualArithmeticConversions()
1357 static QualType
handleComplexIntConversion(Sema
&S
, ExprResult
&LHS
,
1358 ExprResult
&RHS
, QualType LHSType
,
1360 bool IsCompAssign
) {
1361 const ComplexType
*LHSComplexInt
= LHSType
->getAsComplexIntegerType();
1362 const ComplexType
*RHSComplexInt
= RHSType
->getAsComplexIntegerType();
1364 if (LHSComplexInt
&& RHSComplexInt
) {
1365 QualType LHSEltType
= LHSComplexInt
->getElementType();
1366 QualType RHSEltType
= RHSComplexInt
->getElementType();
1367 QualType ScalarType
=
1368 handleIntegerConversion
<doComplexIntegralCast
, doComplexIntegralCast
>
1369 (S
, LHS
, RHS
, LHSEltType
, RHSEltType
, IsCompAssign
);
1371 return S
.Context
.getComplexType(ScalarType
);
1374 if (LHSComplexInt
) {
1375 QualType LHSEltType
= LHSComplexInt
->getElementType();
1376 QualType ScalarType
=
1377 handleIntegerConversion
<doComplexIntegralCast
, doIntegralCast
>
1378 (S
, LHS
, RHS
, LHSEltType
, RHSType
, IsCompAssign
);
1379 QualType ComplexType
= S
.Context
.getComplexType(ScalarType
);
1380 RHS
= S
.ImpCastExprToType(RHS
.get(), ComplexType
,
1381 CK_IntegralRealToComplex
);
1386 assert(RHSComplexInt
);
1388 QualType RHSEltType
= RHSComplexInt
->getElementType();
1389 QualType ScalarType
=
1390 handleIntegerConversion
<doIntegralCast
, doComplexIntegralCast
>
1391 (S
, LHS
, RHS
, LHSType
, RHSEltType
, IsCompAssign
);
1392 QualType ComplexType
= S
.Context
.getComplexType(ScalarType
);
1395 LHS
= S
.ImpCastExprToType(LHS
.get(), ComplexType
,
1396 CK_IntegralRealToComplex
);
1400 /// Return the rank of a given fixed point or integer type. The value itself
1401 /// doesn't matter, but the values must be increasing with proper increasing
1402 /// rank as described in N1169 4.1.1.
1403 static unsigned GetFixedPointRank(QualType Ty
) {
1404 const auto *BTy
= Ty
->getAs
<BuiltinType
>();
1405 assert(BTy
&& "Expected a builtin type.");
1407 switch (BTy
->getKind()) {
1408 case BuiltinType::ShortFract
:
1409 case BuiltinType::UShortFract
:
1410 case BuiltinType::SatShortFract
:
1411 case BuiltinType::SatUShortFract
:
1413 case BuiltinType::Fract
:
1414 case BuiltinType::UFract
:
1415 case BuiltinType::SatFract
:
1416 case BuiltinType::SatUFract
:
1418 case BuiltinType::LongFract
:
1419 case BuiltinType::ULongFract
:
1420 case BuiltinType::SatLongFract
:
1421 case BuiltinType::SatULongFract
:
1423 case BuiltinType::ShortAccum
:
1424 case BuiltinType::UShortAccum
:
1425 case BuiltinType::SatShortAccum
:
1426 case BuiltinType::SatUShortAccum
:
1428 case BuiltinType::Accum
:
1429 case BuiltinType::UAccum
:
1430 case BuiltinType::SatAccum
:
1431 case BuiltinType::SatUAccum
:
1433 case BuiltinType::LongAccum
:
1434 case BuiltinType::ULongAccum
:
1435 case BuiltinType::SatLongAccum
:
1436 case BuiltinType::SatULongAccum
:
1439 if (BTy
->isInteger())
1441 llvm_unreachable("Unexpected fixed point or integer type");
1445 /// handleFixedPointConversion - Fixed point operations between fixed
1446 /// point types and integers or other fixed point types do not fall under
1447 /// usual arithmetic conversion since these conversions could result in loss
1448 /// of precsision (N1169 4.1.4). These operations should be calculated with
1449 /// the full precision of their result type (N1169 4.1.6.2.1).
1450 static QualType
handleFixedPointConversion(Sema
&S
, QualType LHSTy
,
1452 assert((LHSTy
->isFixedPointType() || RHSTy
->isFixedPointType()) &&
1453 "Expected at least one of the operands to be a fixed point type");
1454 assert((LHSTy
->isFixedPointOrIntegerType() ||
1455 RHSTy
->isFixedPointOrIntegerType()) &&
1456 "Special fixed point arithmetic operation conversions are only "
1457 "applied to ints or other fixed point types");
1459 // If one operand has signed fixed-point type and the other operand has
1460 // unsigned fixed-point type, then the unsigned fixed-point operand is
1461 // converted to its corresponding signed fixed-point type and the resulting
1462 // type is the type of the converted operand.
1463 if (RHSTy
->isSignedFixedPointType() && LHSTy
->isUnsignedFixedPointType())
1464 LHSTy
= S
.Context
.getCorrespondingSignedFixedPointType(LHSTy
);
1465 else if (RHSTy
->isUnsignedFixedPointType() && LHSTy
->isSignedFixedPointType())
1466 RHSTy
= S
.Context
.getCorrespondingSignedFixedPointType(RHSTy
);
1468 // The result type is the type with the highest rank, whereby a fixed-point
1469 // conversion rank is always greater than an integer conversion rank; if the
1470 // type of either of the operands is a saturating fixedpoint type, the result
1471 // type shall be the saturating fixed-point type corresponding to the type
1472 // with the highest rank; the resulting value is converted (taking into
1473 // account rounding and overflow) to the precision of the resulting type.
1474 // Same ranks between signed and unsigned types are resolved earlier, so both
1475 // types are either signed or both unsigned at this point.
1476 unsigned LHSTyRank
= GetFixedPointRank(LHSTy
);
1477 unsigned RHSTyRank
= GetFixedPointRank(RHSTy
);
1479 QualType ResultTy
= LHSTyRank
> RHSTyRank
? LHSTy
: RHSTy
;
1481 if (LHSTy
->isSaturatedFixedPointType() || RHSTy
->isSaturatedFixedPointType())
1482 ResultTy
= S
.Context
.getCorrespondingSaturatedType(ResultTy
);
1487 /// Check that the usual arithmetic conversions can be performed on this pair of
1488 /// expressions that might be of enumeration type.
1489 static void checkEnumArithmeticConversions(Sema
&S
, Expr
*LHS
, Expr
*RHS
,
1491 Sema::ArithConvKind ACK
) {
1492 // C++2a [expr.arith.conv]p1:
1493 // If one operand is of enumeration type and the other operand is of a
1494 // different enumeration type or a floating-point type, this behavior is
1495 // deprecated ([depr.arith.conv.enum]).
1497 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1498 // Eventually we will presumably reject these cases (in C++23 onwards?).
1499 QualType L
= LHS
->getEnumCoercedType(S
.Context
),
1500 R
= RHS
->getEnumCoercedType(S
.Context
);
1501 bool LEnum
= L
->isUnscopedEnumerationType(),
1502 REnum
= R
->isUnscopedEnumerationType();
1503 bool IsCompAssign
= ACK
== Sema::ACK_CompAssign
;
1504 if ((!IsCompAssign
&& LEnum
&& R
->isFloatingType()) ||
1505 (REnum
&& L
->isFloatingType())) {
1506 S
.Diag(Loc
, S
.getLangOpts().CPlusPlus26
1507 ? diag::err_arith_conv_enum_float_cxx26
1508 : S
.getLangOpts().CPlusPlus20
1509 ? diag::warn_arith_conv_enum_float_cxx20
1510 : diag::warn_arith_conv_enum_float
)
1511 << LHS
->getSourceRange() << RHS
->getSourceRange() << (int)ACK
<< LEnum
1513 } else if (!IsCompAssign
&& LEnum
&& REnum
&&
1514 !S
.Context
.hasSameUnqualifiedType(L
, R
)) {
1516 // In C++ 26, usual arithmetic conversions between 2 different enum types
1518 if (S
.getLangOpts().CPlusPlus26
)
1519 DiagID
= diag::err_conv_mixed_enum_types_cxx26
;
1520 else if (!L
->castAs
<EnumType
>()->getDecl()->hasNameForLinkage() ||
1521 !R
->castAs
<EnumType
>()->getDecl()->hasNameForLinkage()) {
1522 // If either enumeration type is unnamed, it's less likely that the
1523 // user cares about this, but this situation is still deprecated in
1524 // C++2a. Use a different warning group.
1525 DiagID
= S
.getLangOpts().CPlusPlus20
1526 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1527 : diag::warn_arith_conv_mixed_anon_enum_types
;
1528 } else if (ACK
== Sema::ACK_Conditional
) {
1529 // Conditional expressions are separated out because they have
1530 // historically had a different warning flag.
1531 DiagID
= S
.getLangOpts().CPlusPlus20
1532 ? diag::warn_conditional_mixed_enum_types_cxx20
1533 : diag::warn_conditional_mixed_enum_types
;
1534 } else if (ACK
== Sema::ACK_Comparison
) {
1535 // Comparison expressions are separated out because they have
1536 // historically had a different warning flag.
1537 DiagID
= S
.getLangOpts().CPlusPlus20
1538 ? diag::warn_comparison_mixed_enum_types_cxx20
1539 : diag::warn_comparison_mixed_enum_types
;
1541 DiagID
= S
.getLangOpts().CPlusPlus20
1542 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1543 : diag::warn_arith_conv_mixed_enum_types
;
1545 S
.Diag(Loc
, DiagID
) << LHS
->getSourceRange() << RHS
->getSourceRange()
1546 << (int)ACK
<< L
<< R
;
1550 /// UsualArithmeticConversions - Performs various conversions that are common to
1551 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1552 /// routine returns the first non-arithmetic type found. The client is
1553 /// responsible for emitting appropriate error diagnostics.
1554 QualType
Sema::UsualArithmeticConversions(ExprResult
&LHS
, ExprResult
&RHS
,
1556 ArithConvKind ACK
) {
1557 checkEnumArithmeticConversions(*this, LHS
.get(), RHS
.get(), Loc
, ACK
);
1559 if (ACK
!= ACK_CompAssign
) {
1560 LHS
= UsualUnaryConversions(LHS
.get());
1561 if (LHS
.isInvalid())
1565 RHS
= UsualUnaryConversions(RHS
.get());
1566 if (RHS
.isInvalid())
1569 // For conversion purposes, we ignore any qualifiers.
1570 // For example, "const float" and "float" are equivalent.
1571 QualType LHSType
= LHS
.get()->getType().getUnqualifiedType();
1572 QualType RHSType
= RHS
.get()->getType().getUnqualifiedType();
1574 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1575 if (const AtomicType
*AtomicLHS
= LHSType
->getAs
<AtomicType
>())
1576 LHSType
= AtomicLHS
->getValueType();
1578 // If both types are identical, no conversion is needed.
1579 if (Context
.hasSameType(LHSType
, RHSType
))
1580 return Context
.getCommonSugaredType(LHSType
, RHSType
);
1582 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1583 // The caller can deal with this (e.g. pointer + int).
1584 if (!LHSType
->isArithmeticType() || !RHSType
->isArithmeticType())
1587 // Apply unary and bitfield promotions to the LHS's type.
1588 QualType LHSUnpromotedType
= LHSType
;
1589 if (Context
.isPromotableIntegerType(LHSType
))
1590 LHSType
= Context
.getPromotedIntegerType(LHSType
);
1591 QualType LHSBitfieldPromoteTy
= Context
.isPromotableBitField(LHS
.get());
1592 if (!LHSBitfieldPromoteTy
.isNull())
1593 LHSType
= LHSBitfieldPromoteTy
;
1594 if (LHSType
!= LHSUnpromotedType
&& ACK
!= ACK_CompAssign
)
1595 LHS
= ImpCastExprToType(LHS
.get(), LHSType
, CK_IntegralCast
);
1597 // If both types are identical, no conversion is needed.
1598 if (Context
.hasSameType(LHSType
, RHSType
))
1599 return Context
.getCommonSugaredType(LHSType
, RHSType
);
1601 // At this point, we have two different arithmetic types.
1603 // Diagnose attempts to convert between __ibm128, __float128 and long double
1604 // where such conversions currently can't be handled.
1605 if (unsupportedTypeConversion(*this, LHSType
, RHSType
))
1608 // Handle complex types first (C99 6.3.1.8p1).
1609 if (LHSType
->isComplexType() || RHSType
->isComplexType())
1610 return handleComplexConversion(*this, LHS
, RHS
, LHSType
, RHSType
,
1611 ACK
== ACK_CompAssign
);
1613 // Now handle "real" floating types (i.e. float, double, long double).
1614 if (LHSType
->isRealFloatingType() || RHSType
->isRealFloatingType())
1615 return handleFloatConversion(*this, LHS
, RHS
, LHSType
, RHSType
,
1616 ACK
== ACK_CompAssign
);
1618 // Handle GCC complex int extension.
1619 if (LHSType
->isComplexIntegerType() || RHSType
->isComplexIntegerType())
1620 return handleComplexIntConversion(*this, LHS
, RHS
, LHSType
, RHSType
,
1621 ACK
== ACK_CompAssign
);
1623 if (LHSType
->isFixedPointType() || RHSType
->isFixedPointType())
1624 return handleFixedPointConversion(*this, LHSType
, RHSType
);
1626 // Finally, we have two differing integer types.
1627 return handleIntegerConversion
<doIntegralCast
, doIntegralCast
>
1628 (*this, LHS
, RHS
, LHSType
, RHSType
, ACK
== ACK_CompAssign
);
1631 //===----------------------------------------------------------------------===//
1632 // Semantic Analysis for various Expression Types
1633 //===----------------------------------------------------------------------===//
1636 ExprResult
Sema::ActOnGenericSelectionExpr(
1637 SourceLocation KeyLoc
, SourceLocation DefaultLoc
, SourceLocation RParenLoc
,
1638 bool PredicateIsExpr
, void *ControllingExprOrType
,
1639 ArrayRef
<ParsedType
> ArgTypes
, ArrayRef
<Expr
*> ArgExprs
) {
1640 unsigned NumAssocs
= ArgTypes
.size();
1641 assert(NumAssocs
== ArgExprs
.size());
1643 TypeSourceInfo
**Types
= new TypeSourceInfo
*[NumAssocs
];
1644 for (unsigned i
= 0; i
< NumAssocs
; ++i
) {
1646 (void) GetTypeFromParser(ArgTypes
[i
], &Types
[i
]);
1651 // If we have a controlling type, we need to convert it from a parsed type
1652 // into a semantic type and then pass that along.
1653 if (!PredicateIsExpr
) {
1654 TypeSourceInfo
*ControllingType
;
1655 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType
),
1657 assert(ControllingType
&& "couldn't get the type out of the parser");
1658 ControllingExprOrType
= ControllingType
;
1661 ExprResult ER
= CreateGenericSelectionExpr(
1662 KeyLoc
, DefaultLoc
, RParenLoc
, PredicateIsExpr
, ControllingExprOrType
,
1663 llvm::ArrayRef(Types
, NumAssocs
), ArgExprs
);
1668 ExprResult
Sema::CreateGenericSelectionExpr(
1669 SourceLocation KeyLoc
, SourceLocation DefaultLoc
, SourceLocation RParenLoc
,
1670 bool PredicateIsExpr
, void *ControllingExprOrType
,
1671 ArrayRef
<TypeSourceInfo
*> Types
, ArrayRef
<Expr
*> Exprs
) {
1672 unsigned NumAssocs
= Types
.size();
1673 assert(NumAssocs
== Exprs
.size());
1674 assert(ControllingExprOrType
&&
1675 "Must have either a controlling expression or a controlling type");
1677 Expr
*ControllingExpr
= nullptr;
1678 TypeSourceInfo
*ControllingType
= nullptr;
1679 if (PredicateIsExpr
) {
1680 // Decay and strip qualifiers for the controlling expression type, and
1681 // handle placeholder type replacement. See committee discussion from WG14
1683 EnterExpressionEvaluationContext
Unevaluated(
1684 *this, Sema::ExpressionEvaluationContext::Unevaluated
);
1685 ExprResult R
= DefaultFunctionArrayLvalueConversion(
1686 reinterpret_cast<Expr
*>(ControllingExprOrType
));
1689 ControllingExpr
= R
.get();
1691 // The extension form uses the type directly rather than converting it.
1692 ControllingType
= reinterpret_cast<TypeSourceInfo
*>(ControllingExprOrType
);
1693 if (!ControllingType
)
1697 bool TypeErrorFound
= false,
1698 IsResultDependent
= ControllingExpr
1699 ? ControllingExpr
->isTypeDependent()
1700 : ControllingType
->getType()->isDependentType(),
1701 ContainsUnexpandedParameterPack
=
1703 ? ControllingExpr
->containsUnexpandedParameterPack()
1704 : ControllingType
->getType()->containsUnexpandedParameterPack();
1706 // The controlling expression is an unevaluated operand, so side effects are
1707 // likely unintended.
1708 if (!inTemplateInstantiation() && !IsResultDependent
&& ControllingExpr
&&
1709 ControllingExpr
->HasSideEffects(Context
, false))
1710 Diag(ControllingExpr
->getExprLoc(),
1711 diag::warn_side_effects_unevaluated_context
);
1713 for (unsigned i
= 0; i
< NumAssocs
; ++i
) {
1714 if (Exprs
[i
]->containsUnexpandedParameterPack())
1715 ContainsUnexpandedParameterPack
= true;
1718 if (Types
[i
]->getType()->containsUnexpandedParameterPack())
1719 ContainsUnexpandedParameterPack
= true;
1721 if (Types
[i
]->getType()->isDependentType()) {
1722 IsResultDependent
= true;
1724 // We relax the restriction on use of incomplete types and non-object
1725 // types with the type-based extension of _Generic. Allowing incomplete
1726 // objects means those can be used as "tags" for a type-safe way to map
1727 // to a value. Similarly, matching on function types rather than
1728 // function pointer types can be useful. However, the restriction on VM
1729 // types makes sense to retain as there are open questions about how
1730 // the selection can be made at compile time.
1732 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1733 // complete object type other than a variably modified type."
1735 if (ControllingExpr
&& Types
[i
]->getType()->isIncompleteType())
1736 D
= diag::err_assoc_type_incomplete
;
1737 else if (ControllingExpr
&& !Types
[i
]->getType()->isObjectType())
1738 D
= diag::err_assoc_type_nonobject
;
1739 else if (Types
[i
]->getType()->isVariablyModifiedType())
1740 D
= diag::err_assoc_type_variably_modified
;
1741 else if (ControllingExpr
) {
1742 // Because the controlling expression undergoes lvalue conversion,
1743 // array conversion, and function conversion, an association which is
1744 // of array type, function type, or is qualified can never be
1745 // reached. We will warn about this so users are less surprised by
1746 // the unreachable association. However, we don't have to handle
1747 // function types; that's not an object type, so it's handled above.
1749 // The logic is somewhat different for C++ because C++ has different
1750 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1751 // If T is a non-class type, the type of the prvalue is the cv-
1752 // unqualified version of T. Otherwise, the type of the prvalue is T.
1753 // The result of these rules is that all qualified types in an
1754 // association in C are unreachable, and in C++, only qualified non-
1755 // class types are unreachable.
1757 // NB: this does not apply when the first operand is a type rather
1758 // than an expression, because the type form does not undergo
1760 unsigned Reason
= 0;
1761 QualType QT
= Types
[i
]->getType();
1762 if (QT
->isArrayType())
1764 else if (QT
.hasQualifiers() &&
1765 (!LangOpts
.CPlusPlus
|| !QT
->isRecordType()))
1769 Diag(Types
[i
]->getTypeLoc().getBeginLoc(),
1770 diag::warn_unreachable_association
)
1771 << QT
<< (Reason
- 1);
1775 Diag(Types
[i
]->getTypeLoc().getBeginLoc(), D
)
1776 << Types
[i
]->getTypeLoc().getSourceRange()
1777 << Types
[i
]->getType();
1778 TypeErrorFound
= true;
1781 // C11 6.5.1.1p2 "No two generic associations in the same generic
1782 // selection shall specify compatible types."
1783 for (unsigned j
= i
+1; j
< NumAssocs
; ++j
)
1784 if (Types
[j
] && !Types
[j
]->getType()->isDependentType() &&
1785 Context
.typesAreCompatible(Types
[i
]->getType(),
1786 Types
[j
]->getType())) {
1787 Diag(Types
[j
]->getTypeLoc().getBeginLoc(),
1788 diag::err_assoc_compatible_types
)
1789 << Types
[j
]->getTypeLoc().getSourceRange()
1790 << Types
[j
]->getType()
1791 << Types
[i
]->getType();
1792 Diag(Types
[i
]->getTypeLoc().getBeginLoc(),
1793 diag::note_compat_assoc
)
1794 << Types
[i
]->getTypeLoc().getSourceRange()
1795 << Types
[i
]->getType();
1796 TypeErrorFound
= true;
1804 // If we determined that the generic selection is result-dependent, don't
1805 // try to compute the result expression.
1806 if (IsResultDependent
) {
1807 if (ControllingExpr
)
1808 return GenericSelectionExpr::Create(Context
, KeyLoc
, ControllingExpr
,
1809 Types
, Exprs
, DefaultLoc
, RParenLoc
,
1810 ContainsUnexpandedParameterPack
);
1811 return GenericSelectionExpr::Create(Context
, KeyLoc
, ControllingType
, Types
,
1812 Exprs
, DefaultLoc
, RParenLoc
,
1813 ContainsUnexpandedParameterPack
);
1816 SmallVector
<unsigned, 1> CompatIndices
;
1817 unsigned DefaultIndex
= -1U;
1818 // Look at the canonical type of the controlling expression in case it was a
1819 // deduced type like __auto_type. However, when issuing diagnostics, use the
1820 // type the user wrote in source rather than the canonical one.
1821 for (unsigned i
= 0; i
< NumAssocs
; ++i
) {
1824 else if (ControllingExpr
&&
1825 Context
.typesAreCompatible(
1826 ControllingExpr
->getType().getCanonicalType(),
1827 Types
[i
]->getType()))
1828 CompatIndices
.push_back(i
);
1829 else if (ControllingType
&&
1830 Context
.typesAreCompatible(
1831 ControllingType
->getType().getCanonicalType(),
1832 Types
[i
]->getType()))
1833 CompatIndices
.push_back(i
);
1836 auto GetControllingRangeAndType
= [](Expr
*ControllingExpr
,
1837 TypeSourceInfo
*ControllingType
) {
1838 // We strip parens here because the controlling expression is typically
1839 // parenthesized in macro definitions.
1840 if (ControllingExpr
)
1841 ControllingExpr
= ControllingExpr
->IgnoreParens();
1843 SourceRange SR
= ControllingExpr
1844 ? ControllingExpr
->getSourceRange()
1845 : ControllingType
->getTypeLoc().getSourceRange();
1846 QualType QT
= ControllingExpr
? ControllingExpr
->getType()
1847 : ControllingType
->getType();
1849 return std::make_pair(SR
, QT
);
1852 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1853 // type compatible with at most one of the types named in its generic
1854 // association list."
1855 if (CompatIndices
.size() > 1) {
1856 auto P
= GetControllingRangeAndType(ControllingExpr
, ControllingType
);
1857 SourceRange SR
= P
.first
;
1858 Diag(SR
.getBegin(), diag::err_generic_sel_multi_match
)
1859 << SR
<< P
.second
<< (unsigned)CompatIndices
.size();
1860 for (unsigned I
: CompatIndices
) {
1861 Diag(Types
[I
]->getTypeLoc().getBeginLoc(),
1862 diag::note_compat_assoc
)
1863 << Types
[I
]->getTypeLoc().getSourceRange()
1864 << Types
[I
]->getType();
1869 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1870 // its controlling expression shall have type compatible with exactly one of
1871 // the types named in its generic association list."
1872 if (DefaultIndex
== -1U && CompatIndices
.size() == 0) {
1873 auto P
= GetControllingRangeAndType(ControllingExpr
, ControllingType
);
1874 SourceRange SR
= P
.first
;
1875 Diag(SR
.getBegin(), diag::err_generic_sel_no_match
) << SR
<< P
.second
;
1879 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1880 // type name that is compatible with the type of the controlling expression,
1881 // then the result expression of the generic selection is the expression
1882 // in that generic association. Otherwise, the result expression of the
1883 // generic selection is the expression in the default generic association."
1884 unsigned ResultIndex
=
1885 CompatIndices
.size() ? CompatIndices
[0] : DefaultIndex
;
1887 if (ControllingExpr
) {
1888 return GenericSelectionExpr::Create(
1889 Context
, KeyLoc
, ControllingExpr
, Types
, Exprs
, DefaultLoc
, RParenLoc
,
1890 ContainsUnexpandedParameterPack
, ResultIndex
);
1892 return GenericSelectionExpr::Create(
1893 Context
, KeyLoc
, ControllingType
, Types
, Exprs
, DefaultLoc
, RParenLoc
,
1894 ContainsUnexpandedParameterPack
, ResultIndex
);
1897 static PredefinedIdentKind
getPredefinedExprKind(tok::TokenKind Kind
) {
1900 llvm_unreachable("unexpected TokenKind");
1901 case tok::kw___func__
:
1902 return PredefinedIdentKind::Func
; // [C99 6.4.2.2]
1903 case tok::kw___FUNCTION__
:
1904 return PredefinedIdentKind::Function
;
1905 case tok::kw___FUNCDNAME__
:
1906 return PredefinedIdentKind::FuncDName
; // [MS]
1907 case tok::kw___FUNCSIG__
:
1908 return PredefinedIdentKind::FuncSig
; // [MS]
1909 case tok::kw_L__FUNCTION__
:
1910 return PredefinedIdentKind::LFunction
; // [MS]
1911 case tok::kw_L__FUNCSIG__
:
1912 return PredefinedIdentKind::LFuncSig
; // [MS]
1913 case tok::kw___PRETTY_FUNCTION__
:
1914 return PredefinedIdentKind::PrettyFunction
; // [GNU]
1918 /// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
1919 /// to determine the value of a PredefinedExpr. This can be either a
1920 /// block, lambda, captured statement, function, otherwise a nullptr.
1921 static Decl
*getPredefinedExprDecl(DeclContext
*DC
) {
1922 while (DC
&& !isa
<BlockDecl
, CapturedDecl
, FunctionDecl
, ObjCMethodDecl
>(DC
))
1923 DC
= DC
->getParent();
1924 return cast_or_null
<Decl
>(DC
);
1927 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1928 /// location of the token and the offset of the ud-suffix within it.
1929 static SourceLocation
getUDSuffixLoc(Sema
&S
, SourceLocation TokLoc
,
1931 return Lexer::AdvanceToTokenCharacter(TokLoc
, Offset
, S
.getSourceManager(),
1935 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1936 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1937 static ExprResult
BuildCookedLiteralOperatorCall(Sema
&S
, Scope
*Scope
,
1938 IdentifierInfo
*UDSuffix
,
1939 SourceLocation UDSuffixLoc
,
1940 ArrayRef
<Expr
*> Args
,
1941 SourceLocation LitEndLoc
) {
1942 assert(Args
.size() <= 2 && "too many arguments for literal operator");
1945 for (unsigned ArgIdx
= 0; ArgIdx
!= Args
.size(); ++ArgIdx
) {
1946 ArgTy
[ArgIdx
] = Args
[ArgIdx
]->getType();
1947 if (ArgTy
[ArgIdx
]->isArrayType())
1948 ArgTy
[ArgIdx
] = S
.Context
.getArrayDecayedType(ArgTy
[ArgIdx
]);
1951 DeclarationName OpName
=
1952 S
.Context
.DeclarationNames
.getCXXLiteralOperatorName(UDSuffix
);
1953 DeclarationNameInfo
OpNameInfo(OpName
, UDSuffixLoc
);
1954 OpNameInfo
.setCXXLiteralOperatorNameLoc(UDSuffixLoc
);
1956 LookupResult
R(S
, OpName
, UDSuffixLoc
, Sema::LookupOrdinaryName
);
1957 if (S
.LookupLiteralOperator(Scope
, R
, llvm::ArrayRef(ArgTy
, Args
.size()),
1958 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1959 /*AllowStringTemplatePack*/ false,
1960 /*DiagnoseMissing*/ true) == Sema::LOLR_Error
)
1963 return S
.BuildLiteralOperatorCall(R
, OpNameInfo
, Args
, LitEndLoc
);
1966 ExprResult
Sema::ActOnUnevaluatedStringLiteral(ArrayRef
<Token
> StringToks
) {
1967 // StringToks needs backing storage as it doesn't hold array elements itself
1968 std::vector
<Token
> ExpandedToks
;
1969 if (getLangOpts().MicrosoftExt
)
1970 StringToks
= ExpandedToks
= ExpandFunctionLocalPredefinedMacros(StringToks
);
1972 StringLiteralParser
Literal(StringToks
, PP
,
1973 StringLiteralEvalMethod::Unevaluated
);
1974 if (Literal
.hadError
)
1977 SmallVector
<SourceLocation
, 4> StringTokLocs
;
1978 for (const Token
&Tok
: StringToks
)
1979 StringTokLocs
.push_back(Tok
.getLocation());
1981 StringLiteral
*Lit
= StringLiteral::Create(
1982 Context
, Literal
.GetString(), StringLiteralKind::Unevaluated
, false, {},
1983 &StringTokLocs
[0], StringTokLocs
.size());
1985 if (!Literal
.getUDSuffix().empty()) {
1986 SourceLocation UDSuffixLoc
=
1987 getUDSuffixLoc(*this, StringTokLocs
[Literal
.getUDSuffixToken()],
1988 Literal
.getUDSuffixOffset());
1989 return ExprError(Diag(UDSuffixLoc
, diag::err_invalid_string_udl
));
1996 Sema::ExpandFunctionLocalPredefinedMacros(ArrayRef
<Token
> Toks
) {
1997 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
1998 // local macros that expand to string literals that may be concatenated.
1999 // These macros are expanded here (in Sema), because StringLiteralParser
2000 // (in Lex) doesn't know the enclosing function (because it hasn't been
2002 assert(getLangOpts().MicrosoftExt
);
2004 // Note: Although function local macros are defined only inside functions,
2005 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2006 // expansion of macros into empty string literals without additional checks.
2007 Decl
*CurrentDecl
= getPredefinedExprDecl(CurContext
);
2009 CurrentDecl
= Context
.getTranslationUnitDecl();
2011 std::vector
<Token
> ExpandedToks
;
2012 ExpandedToks
.reserve(Toks
.size());
2013 for (const Token
&Tok
: Toks
) {
2014 if (!isFunctionLocalStringLiteralMacro(Tok
.getKind(), getLangOpts())) {
2015 assert(tok::isStringLiteral(Tok
.getKind()));
2016 ExpandedToks
.emplace_back(Tok
);
2019 if (isa
<TranslationUnitDecl
>(CurrentDecl
))
2020 Diag(Tok
.getLocation(), diag::ext_predef_outside_function
);
2021 // Stringify predefined expression
2022 Diag(Tok
.getLocation(), diag::ext_string_literal_from_predefined
)
2024 SmallString
<64> Str
;
2025 llvm::raw_svector_ostream
OS(Str
);
2026 Token
&Exp
= ExpandedToks
.emplace_back();
2028 if (Tok
.getKind() == tok::kw_L__FUNCTION__
||
2029 Tok
.getKind() == tok::kw_L__FUNCSIG__
) {
2031 Exp
.setKind(tok::wide_string_literal
);
2033 Exp
.setKind(tok::string_literal
);
2036 << Lexer::Stringify(PredefinedExpr::ComputeName(
2037 getPredefinedExprKind(Tok
.getKind()), CurrentDecl
))
2039 PP
.CreateString(OS
.str(), Exp
, Tok
.getLocation(), Tok
.getEndLoc());
2041 return ExpandedToks
;
2045 Sema::ActOnStringLiteral(ArrayRef
<Token
> StringToks
, Scope
*UDLScope
) {
2046 assert(!StringToks
.empty() && "Must have at least one string!");
2048 // StringToks needs backing storage as it doesn't hold array elements itself
2049 std::vector
<Token
> ExpandedToks
;
2050 if (getLangOpts().MicrosoftExt
)
2051 StringToks
= ExpandedToks
= ExpandFunctionLocalPredefinedMacros(StringToks
);
2053 StringLiteralParser
Literal(StringToks
, PP
);
2054 if (Literal
.hadError
)
2057 SmallVector
<SourceLocation
, 4> StringTokLocs
;
2058 for (const Token
&Tok
: StringToks
)
2059 StringTokLocs
.push_back(Tok
.getLocation());
2061 QualType CharTy
= Context
.CharTy
;
2062 StringLiteralKind Kind
= StringLiteralKind::Ordinary
;
2063 if (Literal
.isWide()) {
2064 CharTy
= Context
.getWideCharType();
2065 Kind
= StringLiteralKind::Wide
;
2066 } else if (Literal
.isUTF8()) {
2067 if (getLangOpts().Char8
)
2068 CharTy
= Context
.Char8Ty
;
2069 else if (getLangOpts().C23
)
2070 CharTy
= Context
.UnsignedCharTy
;
2071 Kind
= StringLiteralKind::UTF8
;
2072 } else if (Literal
.isUTF16()) {
2073 CharTy
= Context
.Char16Ty
;
2074 Kind
= StringLiteralKind::UTF16
;
2075 } else if (Literal
.isUTF32()) {
2076 CharTy
= Context
.Char32Ty
;
2077 Kind
= StringLiteralKind::UTF32
;
2078 } else if (Literal
.isPascal()) {
2079 CharTy
= Context
.UnsignedCharTy
;
2082 // Warn on u8 string literals before C++20 and C23, whose type
2083 // was an array of char before but becomes an array of char8_t.
2084 // In C++20, it cannot be used where a pointer to char is expected.
2085 // In C23, it might have an unexpected value if char was signed.
2086 if (Kind
== StringLiteralKind::UTF8
&&
2087 (getLangOpts().CPlusPlus
2088 ? !getLangOpts().CPlusPlus20
&& !getLangOpts().Char8
2089 : !getLangOpts().C23
)) {
2090 Diag(StringTokLocs
.front(), getLangOpts().CPlusPlus
2091 ? diag::warn_cxx20_compat_utf8_string
2092 : diag::warn_c23_compat_utf8_string
);
2094 // Create removals for all 'u8' prefixes in the string literal(s). This
2095 // ensures C++20/C23 compatibility (but may change the program behavior when
2096 // built by non-Clang compilers for which the execution character set is
2097 // not always UTF-8).
2098 auto RemovalDiag
= PDiag(diag::note_cxx20_c23_compat_utf8_string_remove_u8
);
2099 SourceLocation RemovalDiagLoc
;
2100 for (const Token
&Tok
: StringToks
) {
2101 if (Tok
.getKind() == tok::utf8_string_literal
) {
2102 if (RemovalDiagLoc
.isInvalid())
2103 RemovalDiagLoc
= Tok
.getLocation();
2104 RemovalDiag
<< FixItHint::CreateRemoval(CharSourceRange::getCharRange(
2106 Lexer::AdvanceToTokenCharacter(Tok
.getLocation(), 2,
2107 getSourceManager(), getLangOpts())));
2110 Diag(RemovalDiagLoc
, RemovalDiag
);
2114 Context
.getStringLiteralArrayType(CharTy
, Literal
.GetNumStringChars());
2116 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2117 StringLiteral
*Lit
= StringLiteral::Create(Context
, Literal
.GetString(),
2118 Kind
, Literal
.Pascal
, StrTy
,
2120 StringTokLocs
.size());
2121 if (Literal
.getUDSuffix().empty())
2124 // We're building a user-defined literal.
2125 IdentifierInfo
*UDSuffix
= &Context
.Idents
.get(Literal
.getUDSuffix());
2126 SourceLocation UDSuffixLoc
=
2127 getUDSuffixLoc(*this, StringTokLocs
[Literal
.getUDSuffixToken()],
2128 Literal
.getUDSuffixOffset());
2130 // Make sure we're allowed user-defined literals here.
2132 return ExprError(Diag(UDSuffixLoc
, diag::err_invalid_string_udl
));
2134 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2135 // operator "" X (str, len)
2136 QualType SizeType
= Context
.getSizeType();
2138 DeclarationName OpName
=
2139 Context
.DeclarationNames
.getCXXLiteralOperatorName(UDSuffix
);
2140 DeclarationNameInfo
OpNameInfo(OpName
, UDSuffixLoc
);
2141 OpNameInfo
.setCXXLiteralOperatorNameLoc(UDSuffixLoc
);
2143 QualType ArgTy
[] = {
2144 Context
.getArrayDecayedType(StrTy
), SizeType
2147 LookupResult
R(*this, OpName
, UDSuffixLoc
, LookupOrdinaryName
);
2148 switch (LookupLiteralOperator(UDLScope
, R
, ArgTy
,
2149 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2150 /*AllowStringTemplatePack*/ true,
2151 /*DiagnoseMissing*/ true, Lit
)) {
2154 llvm::APInt
Len(Context
.getIntWidth(SizeType
), Literal
.GetNumStringChars());
2155 IntegerLiteral
*LenArg
= IntegerLiteral::Create(Context
, Len
, SizeType
,
2157 Expr
*Args
[] = { Lit
, LenArg
};
2159 return BuildLiteralOperatorCall(R
, OpNameInfo
, Args
, StringTokLocs
.back());
2162 case LOLR_Template
: {
2163 TemplateArgumentListInfo ExplicitArgs
;
2164 TemplateArgument
Arg(Lit
);
2165 TemplateArgumentLocInfo
ArgInfo(Lit
);
2166 ExplicitArgs
.addArgument(TemplateArgumentLoc(Arg
, ArgInfo
));
2167 return BuildLiteralOperatorCall(R
, OpNameInfo
, {}, StringTokLocs
.back(),
2171 case LOLR_StringTemplatePack
: {
2172 TemplateArgumentListInfo ExplicitArgs
;
2174 unsigned CharBits
= Context
.getIntWidth(CharTy
);
2175 bool CharIsUnsigned
= CharTy
->isUnsignedIntegerType();
2176 llvm::APSInt
Value(CharBits
, CharIsUnsigned
);
2178 TemplateArgument
TypeArg(CharTy
);
2179 TemplateArgumentLocInfo
TypeArgInfo(Context
.getTrivialTypeSourceInfo(CharTy
));
2180 ExplicitArgs
.addArgument(TemplateArgumentLoc(TypeArg
, TypeArgInfo
));
2182 for (unsigned I
= 0, N
= Lit
->getLength(); I
!= N
; ++I
) {
2183 Value
= Lit
->getCodeUnit(I
);
2184 TemplateArgument
Arg(Context
, Value
, CharTy
);
2185 TemplateArgumentLocInfo ArgInfo
;
2186 ExplicitArgs
.addArgument(TemplateArgumentLoc(Arg
, ArgInfo
));
2188 return BuildLiteralOperatorCall(R
, OpNameInfo
, {}, StringTokLocs
.back(),
2192 case LOLR_ErrorNoDiagnostic
:
2193 llvm_unreachable("unexpected literal operator lookup result");
2197 llvm_unreachable("unexpected literal operator lookup result");
2201 Sema::BuildDeclRefExpr(ValueDecl
*D
, QualType Ty
, ExprValueKind VK
,
2203 const CXXScopeSpec
*SS
) {
2204 DeclarationNameInfo
NameInfo(D
->getDeclName(), Loc
);
2205 return BuildDeclRefExpr(D
, Ty
, VK
, NameInfo
, SS
);
2209 Sema::BuildDeclRefExpr(ValueDecl
*D
, QualType Ty
, ExprValueKind VK
,
2210 const DeclarationNameInfo
&NameInfo
,
2211 const CXXScopeSpec
*SS
, NamedDecl
*FoundD
,
2212 SourceLocation TemplateKWLoc
,
2213 const TemplateArgumentListInfo
*TemplateArgs
) {
2214 NestedNameSpecifierLoc NNS
=
2215 SS
? SS
->getWithLocInContext(Context
) : NestedNameSpecifierLoc();
2216 return BuildDeclRefExpr(D
, Ty
, VK
, NameInfo
, NNS
, FoundD
, TemplateKWLoc
,
2220 // CUDA/HIP: Check whether a captured reference variable is referencing a
2221 // host variable in a device or host device lambda.
2222 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema
&S
,
2224 if (!S
.getLangOpts().CUDA
|| !VD
->hasInit())
2226 assert(VD
->getType()->isReferenceType());
2228 // Check whether the reference variable is referencing a host variable.
2229 auto *DRE
= dyn_cast
<DeclRefExpr
>(VD
->getInit());
2232 auto *Referee
= dyn_cast
<VarDecl
>(DRE
->getDecl());
2233 if (!Referee
|| !Referee
->hasGlobalStorage() ||
2234 Referee
->hasAttr
<CUDADeviceAttr
>())
2237 // Check whether the current function is a device or host device lambda.
2238 // Check whether the reference variable is a capture by getDeclContext()
2239 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2240 auto *MD
= dyn_cast_or_null
<CXXMethodDecl
>(S
.CurContext
);
2241 if (MD
&& MD
->getParent()->isLambda() &&
2242 MD
->getOverloadedOperator() == OO_Call
&& MD
->hasAttr
<CUDADeviceAttr
>() &&
2243 VD
->getDeclContext() != MD
)
2249 NonOdrUseReason
Sema::getNonOdrUseReasonInCurrentContext(ValueDecl
*D
) {
2250 // A declaration named in an unevaluated operand never constitutes an odr-use.
2251 if (isUnevaluatedContext())
2252 return NOUR_Unevaluated
;
2254 // C++2a [basic.def.odr]p4:
2255 // A variable x whose name appears as a potentially-evaluated expression e
2256 // is odr-used by e unless [...] x is a reference that is usable in
2257 // constant expressions.
2259 // If a reference variable referencing a host variable is captured in a
2260 // device or host device lambda, the value of the referee must be copied
2261 // to the capture and the reference variable must be treated as odr-use
2262 // since the value of the referee is not known at compile time and must
2263 // be loaded from the captured.
2264 if (VarDecl
*VD
= dyn_cast
<VarDecl
>(D
)) {
2265 if (VD
->getType()->isReferenceType() &&
2266 !(getLangOpts().OpenMP
&& OpenMP().isOpenMPCapturedDecl(D
)) &&
2267 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD
) &&
2268 VD
->isUsableInConstantExpressions(Context
))
2269 return NOUR_Constant
;
2272 // All remaining non-variable cases constitute an odr-use. For variables, we
2273 // need to wait and see how the expression is used.
2278 Sema::BuildDeclRefExpr(ValueDecl
*D
, QualType Ty
, ExprValueKind VK
,
2279 const DeclarationNameInfo
&NameInfo
,
2280 NestedNameSpecifierLoc NNS
, NamedDecl
*FoundD
,
2281 SourceLocation TemplateKWLoc
,
2282 const TemplateArgumentListInfo
*TemplateArgs
) {
2283 bool RefersToCapturedVariable
= isa
<VarDecl
, BindingDecl
>(D
) &&
2284 NeedToCaptureVariable(D
, NameInfo
.getLoc());
2286 DeclRefExpr
*E
= DeclRefExpr::Create(
2287 Context
, NNS
, TemplateKWLoc
, D
, RefersToCapturedVariable
, NameInfo
, Ty
,
2288 VK
, FoundD
, TemplateArgs
, getNonOdrUseReasonInCurrentContext(D
));
2289 MarkDeclRefReferenced(E
);
2291 // C++ [except.spec]p17:
2292 // An exception-specification is considered to be needed when:
2293 // - in an expression, the function is the unique lookup result or
2294 // the selected member of a set of overloaded functions.
2296 // We delay doing this until after we've built the function reference and
2297 // marked it as used so that:
2298 // a) if the function is defaulted, we get errors from defining it before /
2299 // instead of errors from computing its exception specification, and
2300 // b) if the function is a defaulted comparison, we can use the body we
2301 // build when defining it as input to the exception specification
2302 // computation rather than computing a new body.
2303 if (const auto *FPT
= Ty
->getAs
<FunctionProtoType
>()) {
2304 if (isUnresolvedExceptionSpec(FPT
->getExceptionSpecType())) {
2305 if (const auto *NewFPT
= ResolveExceptionSpec(NameInfo
.getLoc(), FPT
))
2306 E
->setType(Context
.getQualifiedType(NewFPT
, Ty
.getQualifiers()));
2310 if (getLangOpts().ObjCWeak
&& isa
<VarDecl
>(D
) &&
2311 Ty
.getObjCLifetime() == Qualifiers::OCL_Weak
&& !isUnevaluatedContext() &&
2312 !Diags
.isIgnored(diag::warn_arc_repeated_use_of_weak
, E
->getBeginLoc()))
2313 getCurFunction()->recordUseOfWeak(E
);
2315 const auto *FD
= dyn_cast
<FieldDecl
>(D
);
2316 if (const auto *IFD
= dyn_cast
<IndirectFieldDecl
>(D
))
2317 FD
= IFD
->getAnonField();
2319 UnusedPrivateFields
.remove(FD
);
2320 // Just in case we're building an illegal pointer-to-member.
2321 if (FD
->isBitField())
2322 E
->setObjectKind(OK_BitField
);
2325 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2326 // designates a bit-field.
2327 if (const auto *BD
= dyn_cast
<BindingDecl
>(D
))
2328 if (const auto *BE
= BD
->getBinding())
2329 E
->setObjectKind(BE
->getObjectKind());
2335 Sema::DecomposeUnqualifiedId(const UnqualifiedId
&Id
,
2336 TemplateArgumentListInfo
&Buffer
,
2337 DeclarationNameInfo
&NameInfo
,
2338 const TemplateArgumentListInfo
*&TemplateArgs
) {
2339 if (Id
.getKind() == UnqualifiedIdKind::IK_TemplateId
) {
2340 Buffer
.setLAngleLoc(Id
.TemplateId
->LAngleLoc
);
2341 Buffer
.setRAngleLoc(Id
.TemplateId
->RAngleLoc
);
2343 ASTTemplateArgsPtr
TemplateArgsPtr(Id
.TemplateId
->getTemplateArgs(),
2344 Id
.TemplateId
->NumArgs
);
2345 translateTemplateArguments(TemplateArgsPtr
, Buffer
);
2347 TemplateName TName
= Id
.TemplateId
->Template
.get();
2348 SourceLocation TNameLoc
= Id
.TemplateId
->TemplateNameLoc
;
2349 NameInfo
= Context
.getNameForTemplate(TName
, TNameLoc
);
2350 TemplateArgs
= &Buffer
;
2352 NameInfo
= GetNameFromUnqualifiedId(Id
);
2353 TemplateArgs
= nullptr;
2357 static void emitEmptyLookupTypoDiagnostic(
2358 const TypoCorrection
&TC
, Sema
&SemaRef
, const CXXScopeSpec
&SS
,
2359 DeclarationName Typo
, SourceLocation TypoLoc
, ArrayRef
<Expr
*> Args
,
2360 unsigned DiagnosticID
, unsigned DiagnosticSuggestID
) {
2362 SS
.isEmpty() ? nullptr : SemaRef
.computeDeclContext(SS
, false);
2364 // Emit a special diagnostic for failed member lookups.
2365 // FIXME: computing the declaration context might fail here (?)
2367 SemaRef
.Diag(TypoLoc
, diag::err_no_member
) << Typo
<< Ctx
2370 SemaRef
.Diag(TypoLoc
, DiagnosticID
) << Typo
;
2374 std::string CorrectedStr
= TC
.getAsString(SemaRef
.getLangOpts());
2375 bool DroppedSpecifier
=
2376 TC
.WillReplaceSpecifier() && Typo
.getAsString() == CorrectedStr
;
2377 unsigned NoteID
= TC
.getCorrectionDeclAs
<ImplicitParamDecl
>()
2378 ? diag::note_implicit_param_decl
2379 : diag::note_previous_decl
;
2381 SemaRef
.diagnoseTypo(TC
, SemaRef
.PDiag(DiagnosticSuggestID
) << Typo
,
2382 SemaRef
.PDiag(NoteID
));
2384 SemaRef
.diagnoseTypo(TC
, SemaRef
.PDiag(diag::err_no_member_suggest
)
2385 << Typo
<< Ctx
<< DroppedSpecifier
2387 SemaRef
.PDiag(NoteID
));
2390 bool Sema::DiagnoseDependentMemberLookup(const LookupResult
&R
) {
2391 // During a default argument instantiation the CurContext points
2392 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2393 // function parameter list, hence add an explicit check.
2394 bool isDefaultArgument
=
2395 !CodeSynthesisContexts
.empty() &&
2396 CodeSynthesisContexts
.back().Kind
==
2397 CodeSynthesisContext::DefaultFunctionArgumentInstantiation
;
2398 const auto *CurMethod
= dyn_cast
<CXXMethodDecl
>(CurContext
);
2399 bool isInstance
= CurMethod
&& CurMethod
->isInstance() &&
2400 R
.getNamingClass() == CurMethod
->getParent() &&
2403 // There are two ways we can find a class-scope declaration during template
2404 // instantiation that we did not find in the template definition: if it is a
2405 // member of a dependent base class, or if it is declared after the point of
2406 // use in the same class. Distinguish these by comparing the class in which
2407 // the member was found to the naming class of the lookup.
2408 unsigned DiagID
= diag::err_found_in_dependent_base
;
2409 unsigned NoteID
= diag::note_member_declared_at
;
2410 if (R
.getRepresentativeDecl()->getDeclContext()->Equals(R
.getNamingClass())) {
2411 DiagID
= getLangOpts().MSVCCompat
? diag::ext_found_later_in_class
2412 : diag::err_found_later_in_class
;
2413 } else if (getLangOpts().MSVCCompat
) {
2414 DiagID
= diag::ext_found_in_dependent_base
;
2415 NoteID
= diag::note_dependent_member_use
;
2419 // Give a code modification hint to insert 'this->'.
2420 Diag(R
.getNameLoc(), DiagID
)
2421 << R
.getLookupName()
2422 << FixItHint::CreateInsertion(R
.getNameLoc(), "this->");
2423 CheckCXXThisCapture(R
.getNameLoc());
2425 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2426 // they're not shadowed).
2427 Diag(R
.getNameLoc(), DiagID
) << R
.getLookupName();
2430 for (const NamedDecl
*D
: R
)
2431 Diag(D
->getLocation(), NoteID
);
2433 // Return true if we are inside a default argument instantiation
2434 // and the found name refers to an instance member function, otherwise
2435 // the caller will try to create an implicit member call and this is wrong
2436 // for default arguments.
2438 // FIXME: Is this special case necessary? We could allow the caller to
2440 if (isDefaultArgument
&& ((*R
.begin())->isCXXInstanceMember())) {
2441 Diag(R
.getNameLoc(), diag::err_member_call_without_object
) << 0;
2445 // Tell the callee to try to recover.
2449 bool Sema::DiagnoseEmptyLookup(Scope
*S
, CXXScopeSpec
&SS
, LookupResult
&R
,
2450 CorrectionCandidateCallback
&CCC
,
2451 TemplateArgumentListInfo
*ExplicitTemplateArgs
,
2452 ArrayRef
<Expr
*> Args
, DeclContext
*LookupCtx
,
2454 DeclarationName Name
= R
.getLookupName();
2456 unsigned diagnostic
= diag::err_undeclared_var_use
;
2457 unsigned diagnostic_suggest
= diag::err_undeclared_var_use_suggest
;
2458 if (Name
.getNameKind() == DeclarationName::CXXOperatorName
||
2459 Name
.getNameKind() == DeclarationName::CXXLiteralOperatorName
||
2460 Name
.getNameKind() == DeclarationName::CXXConversionFunctionName
) {
2461 diagnostic
= diag::err_undeclared_use
;
2462 diagnostic_suggest
= diag::err_undeclared_use_suggest
;
2465 // If the original lookup was an unqualified lookup, fake an
2466 // unqualified lookup. This is useful when (for example) the
2467 // original lookup would not have found something because it was a
2470 LookupCtx
? LookupCtx
: (SS
.isEmpty() ? CurContext
: nullptr);
2472 if (isa
<CXXRecordDecl
>(DC
)) {
2473 if (ExplicitTemplateArgs
) {
2474 if (LookupTemplateName(
2475 R
, S
, SS
, Context
.getRecordType(cast
<CXXRecordDecl
>(DC
)),
2476 /*EnteringContext*/ false, TemplateNameIsRequired
,
2477 /*RequiredTemplateKind*/ nullptr, /*AllowTypoCorrection*/ true))
2480 LookupQualifiedName(R
, DC
);
2484 // Don't give errors about ambiguities in this lookup.
2485 R
.suppressDiagnostics();
2487 // If there's a best viable function among the results, only mention
2488 // that one in the notes.
2489 OverloadCandidateSet
Candidates(R
.getNameLoc(),
2490 OverloadCandidateSet::CSK_Normal
);
2491 AddOverloadedCallCandidates(R
, ExplicitTemplateArgs
, Args
, Candidates
);
2492 OverloadCandidateSet::iterator Best
;
2493 if (Candidates
.BestViableFunction(*this, R
.getNameLoc(), Best
) ==
2496 R
.addDecl(Best
->FoundDecl
.getDecl(), Best
->FoundDecl
.getAccess());
2500 return DiagnoseDependentMemberLookup(R
);
2506 DC
= DC
->getLookupParent();
2509 // We didn't find anything, so try to correct for a typo.
2510 TypoCorrection Corrected
;
2512 SourceLocation TypoLoc
= R
.getNameLoc();
2513 assert(!ExplicitTemplateArgs
&&
2514 "Diagnosing an empty lookup with explicit template args!");
2515 *Out
= CorrectTypoDelayed(
2516 R
.getLookupNameInfo(), R
.getLookupKind(), S
, &SS
, CCC
,
2517 [=](const TypoCorrection
&TC
) {
2518 emitEmptyLookupTypoDiagnostic(TC
, *this, SS
, Name
, TypoLoc
, Args
,
2519 diagnostic
, diagnostic_suggest
);
2521 nullptr, CTK_ErrorRecovery
, LookupCtx
);
2524 } else if (S
&& (Corrected
=
2525 CorrectTypo(R
.getLookupNameInfo(), R
.getLookupKind(), S
,
2526 &SS
, CCC
, CTK_ErrorRecovery
, LookupCtx
))) {
2527 std::string
CorrectedStr(Corrected
.getAsString(getLangOpts()));
2528 bool DroppedSpecifier
=
2529 Corrected
.WillReplaceSpecifier() && Name
.getAsString() == CorrectedStr
;
2530 R
.setLookupName(Corrected
.getCorrection());
2532 bool AcceptableWithRecovery
= false;
2533 bool AcceptableWithoutRecovery
= false;
2534 NamedDecl
*ND
= Corrected
.getFoundDecl();
2536 if (Corrected
.isOverloaded()) {
2537 OverloadCandidateSet
OCS(R
.getNameLoc(),
2538 OverloadCandidateSet::CSK_Normal
);
2539 OverloadCandidateSet::iterator Best
;
2540 for (NamedDecl
*CD
: Corrected
) {
2541 if (FunctionTemplateDecl
*FTD
=
2542 dyn_cast
<FunctionTemplateDecl
>(CD
))
2543 AddTemplateOverloadCandidate(
2544 FTD
, DeclAccessPair::make(FTD
, AS_none
), ExplicitTemplateArgs
,
2546 else if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(CD
))
2547 if (!ExplicitTemplateArgs
|| ExplicitTemplateArgs
->size() == 0)
2548 AddOverloadCandidate(FD
, DeclAccessPair::make(FD
, AS_none
),
2551 switch (OCS
.BestViableFunction(*this, R
.getNameLoc(), Best
)) {
2553 ND
= Best
->FoundDecl
;
2554 Corrected
.setCorrectionDecl(ND
);
2557 // FIXME: Arbitrarily pick the first declaration for the note.
2558 Corrected
.setCorrectionDecl(ND
);
2563 if (getLangOpts().CPlusPlus
&& ND
->isCXXClassMember()) {
2564 CXXRecordDecl
*Record
= nullptr;
2565 if (Corrected
.getCorrectionSpecifier()) {
2566 const Type
*Ty
= Corrected
.getCorrectionSpecifier()->getAsType();
2567 Record
= Ty
->getAsCXXRecordDecl();
2570 Record
= cast
<CXXRecordDecl
>(
2571 ND
->getDeclContext()->getRedeclContext());
2572 R
.setNamingClass(Record
);
2575 auto *UnderlyingND
= ND
->getUnderlyingDecl();
2576 AcceptableWithRecovery
= isa
<ValueDecl
>(UnderlyingND
) ||
2577 isa
<FunctionTemplateDecl
>(UnderlyingND
);
2578 // FIXME: If we ended up with a typo for a type name or
2579 // Objective-C class name, we're in trouble because the parser
2580 // is in the wrong place to recover. Suggest the typo
2581 // correction, but don't make it a fix-it since we're not going
2582 // to recover well anyway.
2583 AcceptableWithoutRecovery
= isa
<TypeDecl
>(UnderlyingND
) ||
2584 getAsTypeTemplateDecl(UnderlyingND
) ||
2585 isa
<ObjCInterfaceDecl
>(UnderlyingND
);
2587 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2588 // because we aren't able to recover.
2589 AcceptableWithoutRecovery
= true;
2592 if (AcceptableWithRecovery
|| AcceptableWithoutRecovery
) {
2593 unsigned NoteID
= Corrected
.getCorrectionDeclAs
<ImplicitParamDecl
>()
2594 ? diag::note_implicit_param_decl
2595 : diag::note_previous_decl
;
2597 diagnoseTypo(Corrected
, PDiag(diagnostic_suggest
) << Name
,
2598 PDiag(NoteID
), AcceptableWithRecovery
);
2600 diagnoseTypo(Corrected
, PDiag(diag::err_no_member_suggest
)
2601 << Name
<< computeDeclContext(SS
, false)
2602 << DroppedSpecifier
<< SS
.getRange(),
2603 PDiag(NoteID
), AcceptableWithRecovery
);
2605 // Tell the callee whether to try to recover.
2606 return !AcceptableWithRecovery
;
2611 // Emit a special diagnostic for failed member lookups.
2612 // FIXME: computing the declaration context might fail here (?)
2613 if (!SS
.isEmpty()) {
2614 Diag(R
.getNameLoc(), diag::err_no_member
)
2615 << Name
<< computeDeclContext(SS
, false)
2620 // Give up, we can't recover.
2621 Diag(R
.getNameLoc(), diagnostic
) << Name
;
2625 /// In Microsoft mode, if we are inside a template class whose parent class has
2626 /// dependent base classes, and we can't resolve an unqualified identifier, then
2627 /// assume the identifier is a member of a dependent base class. We can only
2628 /// recover successfully in static methods, instance methods, and other contexts
2629 /// where 'this' is available. This doesn't precisely match MSVC's
2630 /// instantiation model, but it's close enough.
2632 recoverFromMSUnqualifiedLookup(Sema
&S
, ASTContext
&Context
,
2633 DeclarationNameInfo
&NameInfo
,
2634 SourceLocation TemplateKWLoc
,
2635 const TemplateArgumentListInfo
*TemplateArgs
) {
2636 // Only try to recover from lookup into dependent bases in static methods or
2637 // contexts where 'this' is available.
2638 QualType ThisType
= S
.getCurrentThisType();
2639 const CXXRecordDecl
*RD
= nullptr;
2640 if (!ThisType
.isNull())
2641 RD
= ThisType
->getPointeeType()->getAsCXXRecordDecl();
2642 else if (auto *MD
= dyn_cast
<CXXMethodDecl
>(S
.CurContext
))
2643 RD
= MD
->getParent();
2644 if (!RD
|| !RD
->hasDefinition() || !RD
->hasAnyDependentBases())
2647 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2648 // is available, suggest inserting 'this->' as a fixit.
2649 SourceLocation Loc
= NameInfo
.getLoc();
2650 auto DB
= S
.Diag(Loc
, diag::ext_undeclared_unqual_id_with_dependent_base
);
2651 DB
<< NameInfo
.getName() << RD
;
2653 if (!ThisType
.isNull()) {
2654 DB
<< FixItHint::CreateInsertion(Loc
, "this->");
2655 return CXXDependentScopeMemberExpr::Create(
2656 Context
, /*This=*/nullptr, ThisType
, /*IsArrow=*/true,
2657 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc
,
2658 /*FirstQualifierFoundInScope=*/nullptr, NameInfo
, TemplateArgs
);
2661 // Synthesize a fake NNS that points to the derived class. This will
2662 // perform name lookup during template instantiation.
2665 NestedNameSpecifier::Create(Context
, nullptr, true, RD
->getTypeForDecl());
2666 SS
.MakeTrivial(Context
, NNS
, SourceRange(Loc
, Loc
));
2667 return DependentScopeDeclRefExpr::Create(
2668 Context
, SS
.getWithLocInContext(Context
), TemplateKWLoc
, NameInfo
,
2673 Sema::ActOnIdExpression(Scope
*S
, CXXScopeSpec
&SS
,
2674 SourceLocation TemplateKWLoc
, UnqualifiedId
&Id
,
2675 bool HasTrailingLParen
, bool IsAddressOfOperand
,
2676 CorrectionCandidateCallback
*CCC
,
2677 bool IsInlineAsmIdentifier
, Token
*KeywordReplacement
) {
2678 assert(!(IsAddressOfOperand
&& HasTrailingLParen
) &&
2679 "cannot be direct & operand and have a trailing lparen");
2683 TemplateArgumentListInfo TemplateArgsBuffer
;
2685 // Decompose the UnqualifiedId into the following data.
2686 DeclarationNameInfo NameInfo
;
2687 const TemplateArgumentListInfo
*TemplateArgs
;
2688 DecomposeUnqualifiedId(Id
, TemplateArgsBuffer
, NameInfo
, TemplateArgs
);
2690 DeclarationName Name
= NameInfo
.getName();
2691 IdentifierInfo
*II
= Name
.getAsIdentifierInfo();
2692 SourceLocation NameLoc
= NameInfo
.getLoc();
2694 if (II
&& II
->isEditorPlaceholder()) {
2695 // FIXME: When typed placeholders are supported we can create a typed
2696 // placeholder expression node.
2700 // This specially handles arguments of attributes appertains to a type of C
2701 // struct field such that the name lookup within a struct finds the member
2702 // name, which is not the case for other contexts in C.
2703 if (isAttrContext() && !getLangOpts().CPlusPlus
&& S
->isClassScope()) {
2704 // See if this is reference to a field of struct.
2705 LookupResult
R(*this, NameInfo
, LookupMemberName
);
2706 // LookupName handles a name lookup from within anonymous struct.
2707 if (LookupName(R
, S
)) {
2708 if (auto *VD
= dyn_cast
<ValueDecl
>(R
.getFoundDecl())) {
2709 QualType type
= VD
->getType().getNonReferenceType();
2710 // This will eventually be translated into MemberExpr upon
2711 // the use of instantiated struct fields.
2712 return BuildDeclRefExpr(VD
, type
, VK_LValue
, NameLoc
);
2717 // Perform the required lookup.
2718 LookupResult
R(*this, NameInfo
,
2719 (Id
.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam
)
2720 ? LookupObjCImplicitSelfParam
2721 : LookupOrdinaryName
);
2722 if (TemplateKWLoc
.isValid() || TemplateArgs
) {
2723 // Lookup the template name again to correctly establish the context in
2724 // which it was found. This is really unfortunate as we already did the
2725 // lookup to determine that it was a template name in the first place. If
2726 // this becomes a performance hit, we can work harder to preserve those
2727 // results until we get here but it's likely not worth it.
2728 AssumedTemplateKind AssumedTemplate
;
2729 if (LookupTemplateName(R
, S
, SS
, /*ObjectType=*/QualType(),
2730 /*EnteringContext=*/false, TemplateKWLoc
,
2734 if (R
.wasNotFoundInCurrentInstantiation() || SS
.isInvalid())
2735 return ActOnDependentIdExpression(SS
, TemplateKWLoc
, NameInfo
,
2736 IsAddressOfOperand
, TemplateArgs
);
2738 bool IvarLookupFollowUp
= II
&& !SS
.isSet() && getCurMethodDecl();
2739 LookupParsedName(R
, S
, &SS
, /*ObjectType=*/QualType(),
2740 /*AllowBuiltinCreation=*/!IvarLookupFollowUp
);
2742 // If the result might be in a dependent base class, this is a dependent
2744 if (R
.wasNotFoundInCurrentInstantiation() || SS
.isInvalid())
2745 return ActOnDependentIdExpression(SS
, TemplateKWLoc
, NameInfo
,
2746 IsAddressOfOperand
, TemplateArgs
);
2748 // If this reference is in an Objective-C method, then we need to do
2749 // some special Objective-C lookup, too.
2750 if (IvarLookupFollowUp
) {
2751 ExprResult
E(ObjC().LookupInObjCMethod(R
, S
, II
, true));
2755 if (Expr
*Ex
= E
.getAs
<Expr
>())
2760 if (R
.isAmbiguous())
2763 // This could be an implicitly declared function reference if the language
2764 // mode allows it as a feature.
2765 if (R
.empty() && HasTrailingLParen
&& II
&&
2766 getLangOpts().implicitFunctionsAllowed()) {
2767 NamedDecl
*D
= ImplicitlyDefineFunction(NameLoc
, *II
, S
);
2768 if (D
) R
.addDecl(D
);
2771 // Determine whether this name might be a candidate for
2772 // argument-dependent lookup.
2773 bool ADL
= UseArgumentDependentLookup(SS
, R
, HasTrailingLParen
);
2775 if (R
.empty() && !ADL
) {
2776 if (SS
.isEmpty() && getLangOpts().MSVCCompat
) {
2777 if (Expr
*E
= recoverFromMSUnqualifiedLookup(*this, Context
, NameInfo
,
2778 TemplateKWLoc
, TemplateArgs
))
2782 // Don't diagnose an empty lookup for inline assembly.
2783 if (IsInlineAsmIdentifier
)
2786 // If this name wasn't predeclared and if this is not a function
2787 // call, diagnose the problem.
2788 TypoExpr
*TE
= nullptr;
2789 DefaultFilterCCC
DefaultValidator(II
, SS
.isValid() ? SS
.getScopeRep()
2791 DefaultValidator
.IsAddressOfOperand
= IsAddressOfOperand
;
2792 assert((!CCC
|| CCC
->IsAddressOfOperand
== IsAddressOfOperand
) &&
2793 "Typo correction callback misconfigured");
2795 // Make sure the callback knows what the typo being diagnosed is.
2796 CCC
->setTypoName(II
);
2798 CCC
->setTypoNNS(SS
.getScopeRep());
2800 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2801 // a template name, but we happen to have always already looked up the name
2802 // before we get here if it must be a template name.
2803 if (DiagnoseEmptyLookup(S
, SS
, R
, CCC
? *CCC
: DefaultValidator
, nullptr,
2804 {}, nullptr, &TE
)) {
2805 if (TE
&& KeywordReplacement
) {
2806 auto &State
= getTypoExprState(TE
);
2807 auto BestTC
= State
.Consumer
->getNextCorrection();
2808 if (BestTC
.isKeyword()) {
2809 auto *II
= BestTC
.getCorrectionAsIdentifierInfo();
2810 if (State
.DiagHandler
)
2811 State
.DiagHandler(BestTC
);
2812 KeywordReplacement
->startToken();
2813 KeywordReplacement
->setKind(II
->getTokenID());
2814 KeywordReplacement
->setIdentifierInfo(II
);
2815 KeywordReplacement
->setLocation(BestTC
.getCorrectionRange().getBegin());
2816 // Clean up the state associated with the TypoExpr, since it has
2817 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2818 clearDelayedTypo(TE
);
2819 // Signal that a correction to a keyword was performed by returning a
2820 // valid-but-null ExprResult.
2821 return (Expr
*)nullptr;
2823 State
.Consumer
->resetCorrectionStream();
2825 return TE
? TE
: ExprError();
2828 assert(!R
.empty() &&
2829 "DiagnoseEmptyLookup returned false but added no results");
2831 // If we found an Objective-C instance variable, let
2832 // LookupInObjCMethod build the appropriate expression to
2833 // reference the ivar.
2834 if (ObjCIvarDecl
*Ivar
= R
.getAsSingle
<ObjCIvarDecl
>()) {
2836 ExprResult
E(ObjC().LookupInObjCMethod(R
, S
, Ivar
->getIdentifier()));
2837 // In a hopelessly buggy code, Objective-C instance variable
2838 // lookup fails and no expression will be built to reference it.
2839 if (!E
.isInvalid() && !E
.get())
2845 // This is guaranteed from this point on.
2846 assert(!R
.empty() || ADL
);
2848 // Check whether this might be a C++ implicit instance member access.
2849 // C++ [class.mfct.non-static]p3:
2850 // When an id-expression that is not part of a class member access
2851 // syntax and not used to form a pointer to member is used in the
2852 // body of a non-static member function of class X, if name lookup
2853 // resolves the name in the id-expression to a non-static non-type
2854 // member of some class C, the id-expression is transformed into a
2855 // class member access expression using (*this) as the
2856 // postfix-expression to the left of the . operator.
2858 // But we don't actually need to do this for '&' operands if R
2859 // resolved to a function or overloaded function set, because the
2860 // expression is ill-formed if it actually works out to be a
2861 // non-static member function:
2863 // C++ [expr.ref]p4:
2864 // Otherwise, if E1.E2 refers to a non-static member function. . .
2865 // [t]he expression can be used only as the left-hand operand of a
2866 // member function call.
2868 // There are other safeguards against such uses, but it's important
2869 // to get this right here so that we don't end up making a
2870 // spuriously dependent expression if we're inside a dependent
2872 if (isPotentialImplicitMemberAccess(SS
, R
, IsAddressOfOperand
))
2873 return BuildPossibleImplicitMemberExpr(SS
, TemplateKWLoc
, R
, TemplateArgs
,
2876 if (TemplateArgs
|| TemplateKWLoc
.isValid()) {
2878 // In C++1y, if this is a variable template id, then check it
2879 // in BuildTemplateIdExpr().
2880 // The single lookup result must be a variable template declaration.
2881 if (Id
.getKind() == UnqualifiedIdKind::IK_TemplateId
&& Id
.TemplateId
&&
2882 Id
.TemplateId
->Kind
== TNK_Var_template
) {
2883 assert(R
.getAsSingle
<VarTemplateDecl
>() &&
2884 "There should only be one declaration found.");
2887 return BuildTemplateIdExpr(SS
, TemplateKWLoc
, R
, ADL
, TemplateArgs
);
2890 return BuildDeclarationNameExpr(SS
, R
, ADL
);
2893 ExprResult
Sema::BuildQualifiedDeclarationNameExpr(
2894 CXXScopeSpec
&SS
, const DeclarationNameInfo
&NameInfo
,
2895 bool IsAddressOfOperand
, TypeSourceInfo
**RecoveryTSI
) {
2896 LookupResult
R(*this, NameInfo
, LookupOrdinaryName
);
2897 LookupParsedName(R
, /*S=*/nullptr, &SS
, /*ObjectType=*/QualType());
2899 if (R
.isAmbiguous())
2902 if (R
.wasNotFoundInCurrentInstantiation() || SS
.isInvalid())
2903 return BuildDependentDeclRefExpr(SS
, /*TemplateKWLoc=*/SourceLocation(),
2904 NameInfo
, /*TemplateArgs=*/nullptr);
2907 // Don't diagnose problems with invalid record decl, the secondary no_member
2908 // diagnostic during template instantiation is likely bogus, e.g. if a class
2909 // is invalid because it's derived from an invalid base class, then missing
2910 // members were likely supposed to be inherited.
2911 DeclContext
*DC
= computeDeclContext(SS
);
2912 if (const auto *CD
= dyn_cast
<CXXRecordDecl
>(DC
))
2913 if (CD
->isInvalidDecl())
2915 Diag(NameInfo
.getLoc(), diag::err_no_member
)
2916 << NameInfo
.getName() << DC
<< SS
.getRange();
2920 if (const TypeDecl
*TD
= R
.getAsSingle
<TypeDecl
>()) {
2921 // Diagnose a missing typename if this resolved unambiguously to a type in
2922 // a dependent context. If we can recover with a type, downgrade this to
2923 // a warning in Microsoft compatibility mode.
2924 unsigned DiagID
= diag::err_typename_missing
;
2925 if (RecoveryTSI
&& getLangOpts().MSVCCompat
)
2926 DiagID
= diag::ext_typename_missing
;
2927 SourceLocation Loc
= SS
.getBeginLoc();
2928 auto D
= Diag(Loc
, DiagID
);
2929 D
<< SS
.getScopeRep() << NameInfo
.getName().getAsString()
2930 << SourceRange(Loc
, NameInfo
.getEndLoc());
2932 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2937 // Only issue the fixit if we're prepared to recover.
2938 D
<< FixItHint::CreateInsertion(Loc
, "typename ");
2940 // Recover by pretending this was an elaborated type.
2941 QualType Ty
= Context
.getTypeDeclType(TD
);
2943 TLB
.pushTypeSpec(Ty
).setNameLoc(NameInfo
.getLoc());
2945 QualType ET
= getElaboratedType(ElaboratedTypeKeyword::None
, SS
, Ty
);
2946 ElaboratedTypeLoc QTL
= TLB
.push
<ElaboratedTypeLoc
>(ET
);
2947 QTL
.setElaboratedKeywordLoc(SourceLocation());
2948 QTL
.setQualifierLoc(SS
.getWithLocInContext(Context
));
2950 *RecoveryTSI
= TLB
.getTypeSourceInfo(Context
, ET
);
2955 // If necessary, build an implicit class member access.
2956 if (isPotentialImplicitMemberAccess(SS
, R
, IsAddressOfOperand
))
2957 return BuildPossibleImplicitMemberExpr(SS
,
2958 /*TemplateKWLoc=*/SourceLocation(),
2959 R
, /*TemplateArgs=*/nullptr,
2962 return BuildDeclarationNameExpr(SS
, R
, /*ADL=*/false);
2966 Sema::PerformObjectMemberConversion(Expr
*From
,
2967 NestedNameSpecifier
*Qualifier
,
2968 NamedDecl
*FoundDecl
,
2969 NamedDecl
*Member
) {
2970 const auto *RD
= dyn_cast
<CXXRecordDecl
>(Member
->getDeclContext());
2974 QualType DestRecordType
;
2976 QualType FromRecordType
;
2977 QualType FromType
= From
->getType();
2978 bool PointerConversions
= false;
2979 if (isa
<FieldDecl
>(Member
)) {
2980 DestRecordType
= Context
.getCanonicalType(Context
.getTypeDeclType(RD
));
2981 auto FromPtrType
= FromType
->getAs
<PointerType
>();
2982 DestRecordType
= Context
.getAddrSpaceQualType(
2983 DestRecordType
, FromPtrType
2984 ? FromType
->getPointeeType().getAddressSpace()
2985 : FromType
.getAddressSpace());
2988 DestType
= Context
.getPointerType(DestRecordType
);
2989 FromRecordType
= FromPtrType
->getPointeeType();
2990 PointerConversions
= true;
2992 DestType
= DestRecordType
;
2993 FromRecordType
= FromType
;
2995 } else if (const auto *Method
= dyn_cast
<CXXMethodDecl
>(Member
)) {
2996 if (!Method
->isImplicitObjectMemberFunction())
2999 DestType
= Method
->getThisType().getNonReferenceType();
3000 DestRecordType
= Method
->getFunctionObjectParameterType();
3002 if (FromType
->getAs
<PointerType
>()) {
3003 FromRecordType
= FromType
->getPointeeType();
3004 PointerConversions
= true;
3006 FromRecordType
= FromType
;
3007 DestType
= DestRecordType
;
3010 LangAS FromAS
= FromRecordType
.getAddressSpace();
3011 LangAS DestAS
= DestRecordType
.getAddressSpace();
3012 if (FromAS
!= DestAS
) {
3013 QualType FromRecordTypeWithoutAS
=
3014 Context
.removeAddrSpaceQualType(FromRecordType
);
3015 QualType FromTypeWithDestAS
=
3016 Context
.getAddrSpaceQualType(FromRecordTypeWithoutAS
, DestAS
);
3017 if (PointerConversions
)
3018 FromTypeWithDestAS
= Context
.getPointerType(FromTypeWithDestAS
);
3019 From
= ImpCastExprToType(From
, FromTypeWithDestAS
,
3020 CK_AddressSpaceConversion
, From
->getValueKind())
3024 // No conversion necessary.
3028 if (DestType
->isDependentType() || FromType
->isDependentType())
3031 // If the unqualified types are the same, no conversion is necessary.
3032 if (Context
.hasSameUnqualifiedType(FromRecordType
, DestRecordType
))
3035 SourceRange FromRange
= From
->getSourceRange();
3036 SourceLocation FromLoc
= FromRange
.getBegin();
3038 ExprValueKind VK
= From
->getValueKind();
3040 // C++ [class.member.lookup]p8:
3041 // [...] Ambiguities can often be resolved by qualifying a name with its
3044 // If the member was a qualified name and the qualified referred to a
3045 // specific base subobject type, we'll cast to that intermediate type
3046 // first and then to the object in which the member is declared. That allows
3047 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3049 // class Base { public: int x; };
3050 // class Derived1 : public Base { };
3051 // class Derived2 : public Base { };
3052 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3054 // void VeryDerived::f() {
3055 // x = 17; // error: ambiguous base subobjects
3056 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3058 if (Qualifier
&& Qualifier
->getAsType()) {
3059 QualType QType
= QualType(Qualifier
->getAsType(), 0);
3060 assert(QType
->isRecordType() && "lookup done with non-record type");
3062 QualType QRecordType
= QualType(QType
->castAs
<RecordType
>(), 0);
3064 // In C++98, the qualifier type doesn't actually have to be a base
3065 // type of the object type, in which case we just ignore it.
3066 // Otherwise build the appropriate casts.
3067 if (IsDerivedFrom(FromLoc
, FromRecordType
, QRecordType
)) {
3068 CXXCastPath BasePath
;
3069 if (CheckDerivedToBaseConversion(FromRecordType
, QRecordType
,
3070 FromLoc
, FromRange
, &BasePath
))
3073 if (PointerConversions
)
3074 QType
= Context
.getPointerType(QType
);
3075 From
= ImpCastExprToType(From
, QType
, CK_UncheckedDerivedToBase
,
3076 VK
, &BasePath
).get();
3079 FromRecordType
= QRecordType
;
3081 // If the qualifier type was the same as the destination type,
3083 if (Context
.hasSameUnqualifiedType(FromRecordType
, DestRecordType
))
3088 CXXCastPath BasePath
;
3089 if (CheckDerivedToBaseConversion(FromRecordType
, DestRecordType
,
3090 FromLoc
, FromRange
, &BasePath
,
3091 /*IgnoreAccess=*/true))
3094 return ImpCastExprToType(From
, DestType
, CK_UncheckedDerivedToBase
,
3098 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec
&SS
,
3099 const LookupResult
&R
,
3100 bool HasTrailingLParen
) {
3101 // Only when used directly as the postfix-expression of a call.
3102 if (!HasTrailingLParen
)
3105 // Never if a scope specifier was provided.
3106 if (SS
.isNotEmpty())
3109 // Only in C++ or ObjC++.
3110 if (!getLangOpts().CPlusPlus
)
3113 // Turn off ADL when we find certain kinds of declarations during
3115 for (const NamedDecl
*D
: R
) {
3116 // C++0x [basic.lookup.argdep]p3:
3117 // -- a declaration of a class member
3118 // Since using decls preserve this property, we check this on the
3120 if (D
->isCXXClassMember())
3123 // C++0x [basic.lookup.argdep]p3:
3124 // -- a block-scope function declaration that is not a
3125 // using-declaration
3126 // NOTE: we also trigger this for function templates (in fact, we
3127 // don't check the decl type at all, since all other decl types
3128 // turn off ADL anyway).
3129 if (isa
<UsingShadowDecl
>(D
))
3130 D
= cast
<UsingShadowDecl
>(D
)->getTargetDecl();
3131 else if (D
->getLexicalDeclContext()->isFunctionOrMethod())
3134 // C++0x [basic.lookup.argdep]p3:
3135 // -- a declaration that is neither a function or a function
3137 // And also for builtin functions.
3138 if (const auto *FDecl
= dyn_cast
<FunctionDecl
>(D
)) {
3139 // But also builtin functions.
3140 if (FDecl
->getBuiltinID() && FDecl
->isImplicit())
3142 } else if (!isa
<FunctionTemplateDecl
>(D
))
3150 /// Diagnoses obvious problems with the use of the given declaration
3151 /// as an expression. This is only actually called for lookups that
3152 /// were not overloaded, and it doesn't promise that the declaration
3153 /// will in fact be used.
3154 static bool CheckDeclInExpr(Sema
&S
, SourceLocation Loc
, NamedDecl
*D
,
3155 bool AcceptInvalid
) {
3156 if (D
->isInvalidDecl() && !AcceptInvalid
)
3159 if (isa
<TypedefNameDecl
>(D
)) {
3160 S
.Diag(Loc
, diag::err_unexpected_typedef
) << D
->getDeclName();
3164 if (isa
<ObjCInterfaceDecl
>(D
)) {
3165 S
.Diag(Loc
, diag::err_unexpected_interface
) << D
->getDeclName();
3169 if (isa
<NamespaceDecl
>(D
)) {
3170 S
.Diag(Loc
, diag::err_unexpected_namespace
) << D
->getDeclName();
3177 // Certain multiversion types should be treated as overloaded even when there is
3179 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult
&R
) {
3180 assert(R
.isSingleResult() && "Expected only a single result");
3181 const auto *FD
= dyn_cast
<FunctionDecl
>(R
.getFoundDecl());
3183 (FD
->isCPUDispatchMultiVersion() || FD
->isCPUSpecificMultiVersion());
3186 ExprResult
Sema::BuildDeclarationNameExpr(const CXXScopeSpec
&SS
,
3187 LookupResult
&R
, bool NeedsADL
,
3188 bool AcceptInvalidDecl
) {
3189 // If this is a single, fully-resolved result and we don't need ADL,
3190 // just build an ordinary singleton decl ref.
3191 if (!NeedsADL
&& R
.isSingleResult() &&
3192 !R
.getAsSingle
<FunctionTemplateDecl
>() &&
3193 !ShouldLookupResultBeMultiVersionOverload(R
))
3194 return BuildDeclarationNameExpr(SS
, R
.getLookupNameInfo(), R
.getFoundDecl(),
3195 R
.getRepresentativeDecl(), nullptr,
3198 // We only need to check the declaration if there's exactly one
3199 // result, because in the overloaded case the results can only be
3200 // functions and function templates.
3201 if (R
.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R
) &&
3202 CheckDeclInExpr(*this, R
.getNameLoc(), R
.getFoundDecl(),
3206 // Otherwise, just build an unresolved lookup expression. Suppress
3207 // any lookup-related diagnostics; we'll hash these out later, when
3208 // we've picked a target.
3209 R
.suppressDiagnostics();
3211 UnresolvedLookupExpr
*ULE
= UnresolvedLookupExpr::Create(
3212 Context
, R
.getNamingClass(), SS
.getWithLocInContext(Context
),
3213 R
.getLookupNameInfo(), NeedsADL
, R
.begin(), R
.end(),
3214 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3219 static void diagnoseUncapturableValueReferenceOrBinding(Sema
&S
,
3223 ExprResult
Sema::BuildDeclarationNameExpr(
3224 const CXXScopeSpec
&SS
, const DeclarationNameInfo
&NameInfo
, NamedDecl
*D
,
3225 NamedDecl
*FoundD
, const TemplateArgumentListInfo
*TemplateArgs
,
3226 bool AcceptInvalidDecl
) {
3227 assert(D
&& "Cannot refer to a NULL declaration");
3228 assert(!isa
<FunctionTemplateDecl
>(D
) &&
3229 "Cannot refer unambiguously to a function template");
3231 SourceLocation Loc
= NameInfo
.getLoc();
3232 if (CheckDeclInExpr(*this, Loc
, D
, AcceptInvalidDecl
)) {
3233 // Recovery from invalid cases (e.g. D is an invalid Decl).
3234 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3235 // diagnostics, as invalid decls use int as a fallback type.
3236 return CreateRecoveryExpr(NameInfo
.getBeginLoc(), NameInfo
.getEndLoc(), {});
3239 if (TemplateDecl
*TD
= dyn_cast
<TemplateDecl
>(D
)) {
3240 // Specifically diagnose references to class templates that are missing
3241 // a template argument list.
3242 diagnoseMissingTemplateArguments(SS
, /*TemplateKeyword=*/false, TD
, Loc
);
3246 // Make sure that we're referring to a value.
3247 if (!isa
<ValueDecl
, UnresolvedUsingIfExistsDecl
>(D
)) {
3248 Diag(Loc
, diag::err_ref_non_value
) << D
<< SS
.getRange();
3249 Diag(D
->getLocation(), diag::note_declared_at
);
3253 // Check whether this declaration can be used. Note that we suppress
3254 // this check when we're going to perform argument-dependent lookup
3255 // on this function name, because this might not be the function
3256 // that overload resolution actually selects.
3257 if (DiagnoseUseOfDecl(D
, Loc
))
3260 auto *VD
= cast
<ValueDecl
>(D
);
3262 // Only create DeclRefExpr's for valid Decl's.
3263 if (VD
->isInvalidDecl() && !AcceptInvalidDecl
)
3266 // Handle members of anonymous structs and unions. If we got here,
3267 // and the reference is to a class member indirect field, then this
3268 // must be the subject of a pointer-to-member expression.
3269 if (auto *IndirectField
= dyn_cast
<IndirectFieldDecl
>(VD
);
3270 IndirectField
&& !IndirectField
->isCXXClassMember())
3271 return BuildAnonymousStructUnionMemberReference(SS
, NameInfo
.getLoc(),
3274 QualType type
= VD
->getType();
3277 ExprValueKind valueKind
= VK_PRValue
;
3279 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3280 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3281 // is expanded by some outer '...' in the context of the use.
3282 type
= type
.getNonPackExpansionType();
3284 switch (D
->getKind()) {
3285 // Ignore all the non-ValueDecl kinds.
3286 #define ABSTRACT_DECL(kind)
3287 #define VALUE(type, base)
3288 #define DECL(type, base) case Decl::type:
3289 #include "clang/AST/DeclNodes.inc"
3290 llvm_unreachable("invalid value decl kind");
3292 // These shouldn't make it here.
3293 case Decl::ObjCAtDefsField
:
3294 llvm_unreachable("forming non-member reference to ivar?");
3296 // Enum constants are always r-values and never references.
3297 // Unresolved using declarations are dependent.
3298 case Decl::EnumConstant
:
3299 case Decl::UnresolvedUsingValue
:
3300 case Decl::OMPDeclareReduction
:
3301 case Decl::OMPDeclareMapper
:
3302 valueKind
= VK_PRValue
;
3305 // Fields and indirect fields that got here must be for
3306 // pointer-to-member expressions; we just call them l-values for
3307 // internal consistency, because this subexpression doesn't really
3308 // exist in the high-level semantics.
3310 case Decl::IndirectField
:
3311 case Decl::ObjCIvar
:
3312 assert((getLangOpts().CPlusPlus
|| isAttrContext()) &&
3313 "building reference to field in C?");
3315 // These can't have reference type in well-formed programs, but
3316 // for internal consistency we do this anyway.
3317 type
= type
.getNonReferenceType();
3318 valueKind
= VK_LValue
;
3321 // Non-type template parameters are either l-values or r-values
3322 // depending on the type.
3323 case Decl::NonTypeTemplateParm
: {
3324 if (const ReferenceType
*reftype
= type
->getAs
<ReferenceType
>()) {
3325 type
= reftype
->getPointeeType();
3326 valueKind
= VK_LValue
; // even if the parameter is an r-value reference
3330 // [expr.prim.id.unqual]p2:
3331 // If the entity is a template parameter object for a template
3332 // parameter of type T, the type of the expression is const T.
3333 // [...] The expression is an lvalue if the entity is a [...] template
3334 // parameter object.
3335 if (type
->isRecordType()) {
3336 type
= type
.getUnqualifiedType().withConst();
3337 valueKind
= VK_LValue
;
3341 // For non-references, we need to strip qualifiers just in case
3342 // the template parameter was declared as 'const int' or whatever.
3343 valueKind
= VK_PRValue
;
3344 type
= type
.getUnqualifiedType();
3349 case Decl::VarTemplateSpecialization
:
3350 case Decl::VarTemplatePartialSpecialization
:
3351 case Decl::Decomposition
:
3352 case Decl::OMPCapturedExpr
:
3353 // In C, "extern void blah;" is valid and is an r-value.
3354 if (!getLangOpts().CPlusPlus
&& !type
.hasQualifiers() &&
3355 type
->isVoidType()) {
3356 valueKind
= VK_PRValue
;
3361 case Decl::ImplicitParam
:
3362 case Decl::ParmVar
: {
3363 // These are always l-values.
3364 valueKind
= VK_LValue
;
3365 type
= type
.getNonReferenceType();
3367 // FIXME: Does the addition of const really only apply in
3368 // potentially-evaluated contexts? Since the variable isn't actually
3369 // captured in an unevaluated context, it seems that the answer is no.
3370 if (!isUnevaluatedContext()) {
3371 QualType CapturedType
= getCapturedDeclRefType(cast
<VarDecl
>(VD
), Loc
);
3372 if (!CapturedType
.isNull())
3373 type
= CapturedType
;
3380 // These are always lvalues.
3381 valueKind
= VK_LValue
;
3382 type
= type
.getNonReferenceType();
3385 case Decl::Function
: {
3386 if (unsigned BID
= cast
<FunctionDecl
>(VD
)->getBuiltinID()) {
3387 if (!Context
.BuiltinInfo
.isDirectlyAddressable(BID
)) {
3388 type
= Context
.BuiltinFnTy
;
3389 valueKind
= VK_PRValue
;
3394 const FunctionType
*fty
= type
->castAs
<FunctionType
>();
3396 // If we're referring to a function with an __unknown_anytype
3397 // result type, make the entire expression __unknown_anytype.
3398 if (fty
->getReturnType() == Context
.UnknownAnyTy
) {
3399 type
= Context
.UnknownAnyTy
;
3400 valueKind
= VK_PRValue
;
3404 // Functions are l-values in C++.
3405 if (getLangOpts().CPlusPlus
) {
3406 valueKind
= VK_LValue
;
3410 // C99 DR 316 says that, if a function type comes from a
3411 // function definition (without a prototype), that type is only
3412 // used for checking compatibility. Therefore, when referencing
3413 // the function, we pretend that we don't have the full function
3415 if (!cast
<FunctionDecl
>(VD
)->hasPrototype() && isa
<FunctionProtoType
>(fty
))
3416 type
= Context
.getFunctionNoProtoType(fty
->getReturnType(),
3419 // Functions are r-values in C.
3420 valueKind
= VK_PRValue
;
3424 case Decl::CXXDeductionGuide
:
3425 llvm_unreachable("building reference to deduction guide");
3427 case Decl::MSProperty
:
3429 case Decl::TemplateParamObject
:
3430 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3431 // capture in OpenMP, or duplicated between host and device?
3432 valueKind
= VK_LValue
;
3435 case Decl::UnnamedGlobalConstant
:
3436 valueKind
= VK_LValue
;
3439 case Decl::CXXMethod
:
3440 // If we're referring to a method with an __unknown_anytype
3441 // result type, make the entire expression __unknown_anytype.
3442 // This should only be possible with a type written directly.
3443 if (const FunctionProtoType
*proto
=
3444 dyn_cast
<FunctionProtoType
>(VD
->getType()))
3445 if (proto
->getReturnType() == Context
.UnknownAnyTy
) {
3446 type
= Context
.UnknownAnyTy
;
3447 valueKind
= VK_PRValue
;
3451 // C++ methods are l-values if static, r-values if non-static.
3452 if (cast
<CXXMethodDecl
>(VD
)->isStatic()) {
3453 valueKind
= VK_LValue
;
3458 case Decl::CXXConversion
:
3459 case Decl::CXXDestructor
:
3460 case Decl::CXXConstructor
:
3461 valueKind
= VK_PRValue
;
3466 BuildDeclRefExpr(VD
, type
, valueKind
, NameInfo
, &SS
, FoundD
,
3467 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs
);
3468 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3469 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3470 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3472 if (VD
->isInvalidDecl() && E
)
3473 return CreateRecoveryExpr(E
->getBeginLoc(), E
->getEndLoc(), {E
});
3477 static void ConvertUTF8ToWideString(unsigned CharByteWidth
, StringRef Source
,
3478 SmallString
<32> &Target
) {
3479 Target
.resize(CharByteWidth
* (Source
.size() + 1));
3480 char *ResultPtr
= &Target
[0];
3481 const llvm::UTF8
*ErrorPtr
;
3483 llvm::ConvertUTF8toWide(CharByteWidth
, Source
, ResultPtr
, ErrorPtr
);
3486 Target
.resize(ResultPtr
- &Target
[0]);
3489 ExprResult
Sema::BuildPredefinedExpr(SourceLocation Loc
,
3490 PredefinedIdentKind IK
) {
3491 Decl
*currentDecl
= getPredefinedExprDecl(CurContext
);
3493 Diag(Loc
, diag::ext_predef_outside_function
);
3494 currentDecl
= Context
.getTranslationUnitDecl();
3498 StringLiteral
*SL
= nullptr;
3499 if (cast
<DeclContext
>(currentDecl
)->isDependentContext())
3500 ResTy
= Context
.DependentTy
;
3502 // Pre-defined identifiers are of type char[x], where x is the length of
3504 bool ForceElaboratedPrinting
=
3505 IK
== PredefinedIdentKind::Function
&& getLangOpts().MSVCCompat
;
3507 PredefinedExpr::ComputeName(IK
, currentDecl
, ForceElaboratedPrinting
);
3508 unsigned Length
= Str
.length();
3510 llvm::APInt
LengthI(32, Length
+ 1);
3511 if (IK
== PredefinedIdentKind::LFunction
||
3512 IK
== PredefinedIdentKind::LFuncSig
) {
3514 Context
.adjustStringLiteralBaseType(Context
.WideCharTy
.withConst());
3515 SmallString
<32> RawChars
;
3516 ConvertUTF8ToWideString(Context
.getTypeSizeInChars(ResTy
).getQuantity(),
3518 ResTy
= Context
.getConstantArrayType(ResTy
, LengthI
, nullptr,
3519 ArraySizeModifier::Normal
,
3520 /*IndexTypeQuals*/ 0);
3521 SL
= StringLiteral::Create(Context
, RawChars
, StringLiteralKind::Wide
,
3522 /*Pascal*/ false, ResTy
, Loc
);
3524 ResTy
= Context
.adjustStringLiteralBaseType(Context
.CharTy
.withConst());
3525 ResTy
= Context
.getConstantArrayType(ResTy
, LengthI
, nullptr,
3526 ArraySizeModifier::Normal
,
3527 /*IndexTypeQuals*/ 0);
3528 SL
= StringLiteral::Create(Context
, Str
, StringLiteralKind::Ordinary
,
3529 /*Pascal*/ false, ResTy
, Loc
);
3533 return PredefinedExpr::Create(Context
, Loc
, ResTy
, IK
, LangOpts
.MicrosoftExt
,
3537 ExprResult
Sema::ActOnPredefinedExpr(SourceLocation Loc
, tok::TokenKind Kind
) {
3538 return BuildPredefinedExpr(Loc
, getPredefinedExprKind(Kind
));
3541 ExprResult
Sema::ActOnCharacterConstant(const Token
&Tok
, Scope
*UDLScope
) {
3542 SmallString
<16> CharBuffer
;
3543 bool Invalid
= false;
3544 StringRef ThisTok
= PP
.getSpelling(Tok
, CharBuffer
, &Invalid
);
3548 CharLiteralParser
Literal(ThisTok
.begin(), ThisTok
.end(), Tok
.getLocation(),
3550 if (Literal
.hadError())
3554 if (Literal
.isWide())
3555 Ty
= Context
.WideCharTy
; // L'x' -> wchar_t in C and C++.
3556 else if (Literal
.isUTF8() && getLangOpts().C23
)
3557 Ty
= Context
.UnsignedCharTy
; // u8'x' -> unsigned char in C23
3558 else if (Literal
.isUTF8() && getLangOpts().Char8
)
3559 Ty
= Context
.Char8Ty
; // u8'x' -> char8_t when it exists.
3560 else if (Literal
.isUTF16())
3561 Ty
= Context
.Char16Ty
; // u'x' -> char16_t in C11 and C++11.
3562 else if (Literal
.isUTF32())
3563 Ty
= Context
.Char32Ty
; // U'x' -> char32_t in C11 and C++11.
3564 else if (!getLangOpts().CPlusPlus
|| Literal
.isMultiChar())
3565 Ty
= Context
.IntTy
; // 'x' -> int in C, 'wxyz' -> int in C++.
3567 Ty
= Context
.CharTy
; // 'x' -> char in C++;
3568 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3570 CharacterLiteralKind Kind
= CharacterLiteralKind::Ascii
;
3571 if (Literal
.isWide())
3572 Kind
= CharacterLiteralKind::Wide
;
3573 else if (Literal
.isUTF16())
3574 Kind
= CharacterLiteralKind::UTF16
;
3575 else if (Literal
.isUTF32())
3576 Kind
= CharacterLiteralKind::UTF32
;
3577 else if (Literal
.isUTF8())
3578 Kind
= CharacterLiteralKind::UTF8
;
3580 Expr
*Lit
= new (Context
) CharacterLiteral(Literal
.getValue(), Kind
, Ty
,
3583 if (Literal
.getUDSuffix().empty())
3586 // We're building a user-defined literal.
3587 IdentifierInfo
*UDSuffix
= &Context
.Idents
.get(Literal
.getUDSuffix());
3588 SourceLocation UDSuffixLoc
=
3589 getUDSuffixLoc(*this, Tok
.getLocation(), Literal
.getUDSuffixOffset());
3591 // Make sure we're allowed user-defined literals here.
3593 return ExprError(Diag(UDSuffixLoc
, diag::err_invalid_character_udl
));
3595 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3596 // operator "" X (ch)
3597 return BuildCookedLiteralOperatorCall(*this, UDLScope
, UDSuffix
, UDSuffixLoc
,
3598 Lit
, Tok
.getLocation());
3601 ExprResult
Sema::ActOnIntegerConstant(SourceLocation Loc
, int64_t Val
) {
3602 unsigned IntSize
= Context
.getTargetInfo().getIntWidth();
3603 return IntegerLiteral::Create(Context
,
3604 llvm::APInt(IntSize
, Val
, /*isSigned=*/true),
3605 Context
.IntTy
, Loc
);
3608 static Expr
*BuildFloatingLiteral(Sema
&S
, NumericLiteralParser
&Literal
,
3609 QualType Ty
, SourceLocation Loc
) {
3610 const llvm::fltSemantics
&Format
= S
.Context
.getFloatTypeSemantics(Ty
);
3612 using llvm::APFloat
;
3613 APFloat
Val(Format
);
3615 llvm::RoundingMode RM
= S
.CurFPFeatures
.getRoundingMode();
3616 if (RM
== llvm::RoundingMode::Dynamic
)
3617 RM
= llvm::RoundingMode::NearestTiesToEven
;
3618 APFloat::opStatus result
= Literal
.GetFloatValue(Val
, RM
);
3620 // Overflow is always an error, but underflow is only an error if
3621 // we underflowed to zero (APFloat reports denormals as underflow).
3622 if ((result
& APFloat::opOverflow
) ||
3623 ((result
& APFloat::opUnderflow
) && Val
.isZero())) {
3624 unsigned diagnostic
;
3625 SmallString
<20> buffer
;
3626 if (result
& APFloat::opOverflow
) {
3627 diagnostic
= diag::warn_float_overflow
;
3628 APFloat::getLargest(Format
).toString(buffer
);
3630 diagnostic
= diag::warn_float_underflow
;
3631 APFloat::getSmallest(Format
).toString(buffer
);
3634 S
.Diag(Loc
, diagnostic
) << Ty
<< buffer
.str();
3637 bool isExact
= (result
== APFloat::opOK
);
3638 return FloatingLiteral::Create(S
.Context
, Val
, isExact
, Ty
, Loc
);
3641 bool Sema::CheckLoopHintExpr(Expr
*E
, SourceLocation Loc
, bool AllowZero
) {
3642 assert(E
&& "Invalid expression");
3644 if (E
->isValueDependent())
3647 QualType QT
= E
->getType();
3648 if (!QT
->isIntegerType() || QT
->isBooleanType() || QT
->isCharType()) {
3649 Diag(E
->getExprLoc(), diag::err_pragma_loop_invalid_argument_type
) << QT
;
3653 llvm::APSInt ValueAPS
;
3654 ExprResult R
= VerifyIntegerConstantExpression(E
, &ValueAPS
);
3659 // GCC allows the value of unroll count to be 0.
3660 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3661 // "The values of 0 and 1 block any unrolling of the loop."
3662 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3663 // '#pragma unroll' cases.
3664 bool ValueIsPositive
=
3665 AllowZero
? ValueAPS
.isNonNegative() : ValueAPS
.isStrictlyPositive();
3666 if (!ValueIsPositive
|| ValueAPS
.getActiveBits() > 31) {
3667 Diag(E
->getExprLoc(), diag::err_requires_positive_value
)
3668 << toString(ValueAPS
, 10) << ValueIsPositive
;
3675 ExprResult
Sema::ActOnNumericConstant(const Token
&Tok
, Scope
*UDLScope
) {
3676 // Fast path for a single digit (which is quite common). A single digit
3677 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3678 if (Tok
.getLength() == 1 || Tok
.getKind() == tok::binary_data
) {
3679 const uint8_t Val
= PP
.getSpellingOfSingleCharacterNumericConstant(Tok
);
3680 return ActOnIntegerConstant(Tok
.getLocation(), Val
);
3683 SmallString
<128> SpellingBuffer
;
3684 // NumericLiteralParser wants to overread by one character. Add padding to
3685 // the buffer in case the token is copied to the buffer. If getSpelling()
3686 // returns a StringRef to the memory buffer, it should have a null char at
3687 // the EOF, so it is also safe.
3688 SpellingBuffer
.resize(Tok
.getLength() + 1);
3690 // Get the spelling of the token, which eliminates trigraphs, etc.
3691 bool Invalid
= false;
3692 StringRef TokSpelling
= PP
.getSpelling(Tok
, SpellingBuffer
, &Invalid
);
3696 NumericLiteralParser
Literal(TokSpelling
, Tok
.getLocation(),
3697 PP
.getSourceManager(), PP
.getLangOpts(),
3698 PP
.getTargetInfo(), PP
.getDiagnostics());
3699 if (Literal
.hadError
)
3702 if (Literal
.hasUDSuffix()) {
3703 // We're building a user-defined literal.
3704 const IdentifierInfo
*UDSuffix
= &Context
.Idents
.get(Literal
.getUDSuffix());
3705 SourceLocation UDSuffixLoc
=
3706 getUDSuffixLoc(*this, Tok
.getLocation(), Literal
.getUDSuffixOffset());
3708 // Make sure we're allowed user-defined literals here.
3710 return ExprError(Diag(UDSuffixLoc
, diag::err_invalid_numeric_udl
));
3713 if (Literal
.isFloatingLiteral()) {
3714 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3715 // long double, the literal is treated as a call of the form
3716 // operator "" X (f L)
3717 CookedTy
= Context
.LongDoubleTy
;
3719 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3720 // unsigned long long, the literal is treated as a call of the form
3721 // operator "" X (n ULL)
3722 CookedTy
= Context
.UnsignedLongLongTy
;
3725 DeclarationName OpName
=
3726 Context
.DeclarationNames
.getCXXLiteralOperatorName(UDSuffix
);
3727 DeclarationNameInfo
OpNameInfo(OpName
, UDSuffixLoc
);
3728 OpNameInfo
.setCXXLiteralOperatorNameLoc(UDSuffixLoc
);
3730 SourceLocation TokLoc
= Tok
.getLocation();
3732 // Perform literal operator lookup to determine if we're building a raw
3733 // literal or a cooked one.
3734 LookupResult
R(*this, OpName
, UDSuffixLoc
, LookupOrdinaryName
);
3735 switch (LookupLiteralOperator(UDLScope
, R
, CookedTy
,
3736 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3737 /*AllowStringTemplatePack*/ false,
3738 /*DiagnoseMissing*/ !Literal
.isImaginary
)) {
3739 case LOLR_ErrorNoDiagnostic
:
3740 // Lookup failure for imaginary constants isn't fatal, there's still the
3741 // GNU extension producing _Complex types.
3747 if (Literal
.isFloatingLiteral()) {
3748 Lit
= BuildFloatingLiteral(*this, Literal
, CookedTy
, Tok
.getLocation());
3750 llvm::APInt
ResultVal(Context
.getTargetInfo().getLongLongWidth(), 0);
3751 if (Literal
.GetIntegerValue(ResultVal
))
3752 Diag(Tok
.getLocation(), diag::err_integer_literal_too_large
)
3753 << /* Unsigned */ 1;
3754 Lit
= IntegerLiteral::Create(Context
, ResultVal
, CookedTy
,
3757 return BuildLiteralOperatorCall(R
, OpNameInfo
, Lit
, TokLoc
);
3761 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3762 // literal is treated as a call of the form
3763 // operator "" X ("n")
3764 unsigned Length
= Literal
.getUDSuffixOffset();
3765 QualType StrTy
= Context
.getConstantArrayType(
3766 Context
.adjustStringLiteralBaseType(Context
.CharTy
.withConst()),
3767 llvm::APInt(32, Length
+ 1), nullptr, ArraySizeModifier::Normal
, 0);
3769 StringLiteral::Create(Context
, StringRef(TokSpelling
.data(), Length
),
3770 StringLiteralKind::Ordinary
,
3771 /*Pascal*/ false, StrTy
, &TokLoc
, 1);
3772 return BuildLiteralOperatorCall(R
, OpNameInfo
, Lit
, TokLoc
);
3775 case LOLR_Template
: {
3776 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3777 // template), L is treated as a call fo the form
3778 // operator "" X <'c1', 'c2', ... 'ck'>()
3779 // where n is the source character sequence c1 c2 ... ck.
3780 TemplateArgumentListInfo ExplicitArgs
;
3781 unsigned CharBits
= Context
.getIntWidth(Context
.CharTy
);
3782 bool CharIsUnsigned
= Context
.CharTy
->isUnsignedIntegerType();
3783 llvm::APSInt
Value(CharBits
, CharIsUnsigned
);
3784 for (unsigned I
= 0, N
= Literal
.getUDSuffixOffset(); I
!= N
; ++I
) {
3785 Value
= TokSpelling
[I
];
3786 TemplateArgument
Arg(Context
, Value
, Context
.CharTy
);
3787 TemplateArgumentLocInfo ArgInfo
;
3788 ExplicitArgs
.addArgument(TemplateArgumentLoc(Arg
, ArgInfo
));
3790 return BuildLiteralOperatorCall(R
, OpNameInfo
, {}, TokLoc
, &ExplicitArgs
);
3792 case LOLR_StringTemplatePack
:
3793 llvm_unreachable("unexpected literal operator lookup result");
3799 if (Literal
.isFixedPointLiteral()) {
3802 if (Literal
.isAccum
) {
3803 if (Literal
.isHalf
) {
3804 Ty
= Context
.ShortAccumTy
;
3805 } else if (Literal
.isLong
) {
3806 Ty
= Context
.LongAccumTy
;
3808 Ty
= Context
.AccumTy
;
3810 } else if (Literal
.isFract
) {
3811 if (Literal
.isHalf
) {
3812 Ty
= Context
.ShortFractTy
;
3813 } else if (Literal
.isLong
) {
3814 Ty
= Context
.LongFractTy
;
3816 Ty
= Context
.FractTy
;
3820 if (Literal
.isUnsigned
) Ty
= Context
.getCorrespondingUnsignedType(Ty
);
3822 bool isSigned
= !Literal
.isUnsigned
;
3823 unsigned scale
= Context
.getFixedPointScale(Ty
);
3824 unsigned bit_width
= Context
.getTypeInfo(Ty
).Width
;
3826 llvm::APInt
Val(bit_width
, 0, isSigned
);
3827 bool Overflowed
= Literal
.GetFixedPointValue(Val
, scale
);
3828 bool ValIsZero
= Val
.isZero() && !Overflowed
;
3830 auto MaxVal
= Context
.getFixedPointMax(Ty
).getValue();
3831 if (Literal
.isFract
&& Val
== MaxVal
+ 1 && !ValIsZero
)
3832 // Clause 6.4.4 - The value of a constant shall be in the range of
3833 // representable values for its type, with exception for constants of a
3834 // fract type with a value of exactly 1; such a constant shall denote
3835 // the maximal value for the type.
3837 else if (Val
.ugt(MaxVal
) || Overflowed
)
3838 Diag(Tok
.getLocation(), diag::err_too_large_for_fixed_point
);
3840 Res
= FixedPointLiteral::CreateFromRawInt(Context
, Val
, Ty
,
3841 Tok
.getLocation(), scale
);
3842 } else if (Literal
.isFloatingLiteral()) {
3844 if (Literal
.isHalf
){
3845 if (getLangOpts().HLSL
||
3846 getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3847 Ty
= Context
.HalfTy
;
3849 Diag(Tok
.getLocation(), diag::err_half_const_requires_fp16
);
3852 } else if (Literal
.isFloat
)
3853 Ty
= Context
.FloatTy
;
3854 else if (Literal
.isLong
)
3855 Ty
= !getLangOpts().HLSL
? Context
.LongDoubleTy
: Context
.DoubleTy
;
3856 else if (Literal
.isFloat16
)
3857 Ty
= Context
.Float16Ty
;
3858 else if (Literal
.isFloat128
)
3859 Ty
= Context
.Float128Ty
;
3860 else if (getLangOpts().HLSL
)
3861 Ty
= Context
.FloatTy
;
3863 Ty
= Context
.DoubleTy
;
3865 Res
= BuildFloatingLiteral(*this, Literal
, Ty
, Tok
.getLocation());
3867 if (Ty
== Context
.DoubleTy
) {
3868 if (getLangOpts().SinglePrecisionConstants
) {
3869 if (Ty
->castAs
<BuiltinType
>()->getKind() != BuiltinType::Float
) {
3870 Res
= ImpCastExprToType(Res
, Context
.FloatTy
, CK_FloatingCast
).get();
3872 } else if (getLangOpts().OpenCL
&& !getOpenCLOptions().isAvailableOption(
3873 "cl_khr_fp64", getLangOpts())) {
3874 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3875 Diag(Tok
.getLocation(), diag::warn_double_const_requires_fp64
)
3876 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3877 Res
= ImpCastExprToType(Res
, Context
.FloatTy
, CK_FloatingCast
).get();
3880 } else if (!Literal
.isIntegerLiteral()) {
3885 // 'z/uz' literals are a C++23 feature.
3886 if (Literal
.isSizeT
)
3887 Diag(Tok
.getLocation(), getLangOpts().CPlusPlus
3888 ? getLangOpts().CPlusPlus23
3889 ? diag::warn_cxx20_compat_size_t_suffix
3890 : diag::ext_cxx23_size_t_suffix
3891 : diag::err_cxx23_size_t_suffix
);
3893 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
3894 // but we do not currently support the suffix in C++ mode because it's not
3895 // entirely clear whether WG21 will prefer this suffix to return a library
3896 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
3897 // literals are a C++ extension.
3898 if (Literal
.isBitInt
)
3899 PP
.Diag(Tok
.getLocation(),
3900 getLangOpts().CPlusPlus
? diag::ext_cxx_bitint_suffix
3901 : getLangOpts().C23
? diag::warn_c23_compat_bitint_suffix
3902 : diag::ext_c23_bitint_suffix
);
3904 // Get the value in the widest-possible width. What is "widest" depends on
3905 // whether the literal is a bit-precise integer or not. For a bit-precise
3906 // integer type, try to scan the source to determine how many bits are
3907 // needed to represent the value. This may seem a bit expensive, but trying
3908 // to get the integer value from an overly-wide APInt is *extremely*
3909 // expensive, so the naive approach of assuming
3910 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3911 unsigned BitsNeeded
=
3912 Literal
.isBitInt
? llvm::APInt::getSufficientBitsNeeded(
3913 Literal
.getLiteralDigits(), Literal
.getRadix())
3914 : Context
.getTargetInfo().getIntMaxTWidth();
3915 llvm::APInt
ResultVal(BitsNeeded
, 0);
3917 if (Literal
.GetIntegerValue(ResultVal
)) {
3918 // If this value didn't fit into uintmax_t, error and force to ull.
3919 Diag(Tok
.getLocation(), diag::err_integer_literal_too_large
)
3920 << /* Unsigned */ 1;
3921 Ty
= Context
.UnsignedLongLongTy
;
3922 assert(Context
.getTypeSize(Ty
) == ResultVal
.getBitWidth() &&
3923 "long long is not intmax_t?");
3925 // If this value fits into a ULL, try to figure out what else it fits into
3926 // according to the rules of C99 6.4.4.1p5.
3928 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3929 // be an unsigned int.
3930 bool AllowUnsigned
= Literal
.isUnsigned
|| Literal
.getRadix() != 10;
3932 // HLSL doesn't really have `long` or `long long`. We support the `ll`
3933 // suffix for portability of code with C++, but both `l` and `ll` are
3934 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
3936 if (getLangOpts().HLSL
&& !Literal
.isLong
&& Literal
.isLongLong
) {
3937 Literal
.isLong
= true;
3938 Literal
.isLongLong
= false;
3941 // Check from smallest to largest, picking the smallest type we can.
3944 // Microsoft specific integer suffixes are explicitly sized.
3945 if (Literal
.MicrosoftInteger
) {
3946 if (Literal
.MicrosoftInteger
== 8 && !Literal
.isUnsigned
) {
3948 Ty
= Context
.CharTy
;
3950 Width
= Literal
.MicrosoftInteger
;
3951 Ty
= Context
.getIntTypeForBitwidth(Width
,
3952 /*Signed=*/!Literal
.isUnsigned
);
3956 // Bit-precise integer literals are automagically-sized based on the
3957 // width required by the literal.
3958 if (Literal
.isBitInt
) {
3959 // The signed version has one more bit for the sign value. There are no
3960 // zero-width bit-precise integers, even if the literal value is 0.
3961 Width
= std::max(ResultVal
.getActiveBits(), 1u) +
3962 (Literal
.isUnsigned
? 0u : 1u);
3964 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
3965 // and reset the type to the largest supported width.
3966 unsigned int MaxBitIntWidth
=
3967 Context
.getTargetInfo().getMaxBitIntWidth();
3968 if (Width
> MaxBitIntWidth
) {
3969 Diag(Tok
.getLocation(), diag::err_integer_literal_too_large
)
3970 << Literal
.isUnsigned
;
3971 Width
= MaxBitIntWidth
;
3974 // Reset the result value to the smaller APInt and select the correct
3975 // type to be used. Note, we zext even for signed values because the
3976 // literal itself is always an unsigned value (a preceeding - is a
3977 // unary operator, not part of the literal).
3978 ResultVal
= ResultVal
.zextOrTrunc(Width
);
3979 Ty
= Context
.getBitIntType(Literal
.isUnsigned
, Width
);
3982 // Check C++23 size_t literals.
3983 if (Literal
.isSizeT
) {
3984 assert(!Literal
.MicrosoftInteger
&&
3985 "size_t literals can't be Microsoft literals");
3986 unsigned SizeTSize
= Context
.getTargetInfo().getTypeWidth(
3987 Context
.getTargetInfo().getSizeType());
3989 // Does it fit in size_t?
3990 if (ResultVal
.isIntN(SizeTSize
)) {
3991 // Does it fit in ssize_t?
3992 if (!Literal
.isUnsigned
&& ResultVal
[SizeTSize
- 1] == 0)
3993 Ty
= Context
.getSignedSizeType();
3994 else if (AllowUnsigned
)
3995 Ty
= Context
.getSizeType();
4000 if (Ty
.isNull() && !Literal
.isLong
&& !Literal
.isLongLong
&&
4002 // Are int/unsigned possibilities?
4003 unsigned IntSize
= Context
.getTargetInfo().getIntWidth();
4005 // Does it fit in a unsigned int?
4006 if (ResultVal
.isIntN(IntSize
)) {
4007 // Does it fit in a signed int?
4008 if (!Literal
.isUnsigned
&& ResultVal
[IntSize
-1] == 0)
4010 else if (AllowUnsigned
)
4011 Ty
= Context
.UnsignedIntTy
;
4016 // Are long/unsigned long possibilities?
4017 if (Ty
.isNull() && !Literal
.isLongLong
&& !Literal
.isSizeT
) {
4018 unsigned LongSize
= Context
.getTargetInfo().getLongWidth();
4020 // Does it fit in a unsigned long?
4021 if (ResultVal
.isIntN(LongSize
)) {
4022 // Does it fit in a signed long?
4023 if (!Literal
.isUnsigned
&& ResultVal
[LongSize
-1] == 0)
4024 Ty
= Context
.LongTy
;
4025 else if (AllowUnsigned
)
4026 Ty
= Context
.UnsignedLongTy
;
4027 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4029 else if (!getLangOpts().C99
&& !getLangOpts().CPlusPlus11
) {
4030 const unsigned LongLongSize
=
4031 Context
.getTargetInfo().getLongLongWidth();
4032 Diag(Tok
.getLocation(),
4033 getLangOpts().CPlusPlus
4035 ? diag::warn_old_implicitly_unsigned_long_cxx
4036 : /*C++98 UB*/ diag::
4037 ext_old_implicitly_unsigned_long_cxx
4038 : diag::warn_old_implicitly_unsigned_long
)
4039 << (LongLongSize
> LongSize
? /*will have type 'long long'*/ 0
4040 : /*will be ill-formed*/ 1);
4041 Ty
= Context
.UnsignedLongTy
;
4047 // Check long long if needed.
4048 if (Ty
.isNull() && !Literal
.isSizeT
) {
4049 unsigned LongLongSize
= Context
.getTargetInfo().getLongLongWidth();
4051 // Does it fit in a unsigned long long?
4052 if (ResultVal
.isIntN(LongLongSize
)) {
4053 // Does it fit in a signed long long?
4054 // To be compatible with MSVC, hex integer literals ending with the
4055 // LL or i64 suffix are always signed in Microsoft mode.
4056 if (!Literal
.isUnsigned
&& (ResultVal
[LongLongSize
-1] == 0 ||
4057 (getLangOpts().MSVCCompat
&& Literal
.isLongLong
)))
4058 Ty
= Context
.LongLongTy
;
4059 else if (AllowUnsigned
)
4060 Ty
= Context
.UnsignedLongLongTy
;
4061 Width
= LongLongSize
;
4063 // 'long long' is a C99 or C++11 feature, whether the literal
4064 // explicitly specified 'long long' or we needed the extra width.
4065 if (getLangOpts().CPlusPlus
)
4066 Diag(Tok
.getLocation(), getLangOpts().CPlusPlus11
4067 ? diag::warn_cxx98_compat_longlong
4068 : diag::ext_cxx11_longlong
);
4069 else if (!getLangOpts().C99
)
4070 Diag(Tok
.getLocation(), diag::ext_c99_longlong
);
4074 // If we still couldn't decide a type, we either have 'size_t' literal
4075 // that is out of range, or a decimal literal that does not fit in a
4076 // signed long long and has no U suffix.
4078 if (Literal
.isSizeT
)
4079 Diag(Tok
.getLocation(), diag::err_size_t_literal_too_large
)
4080 << Literal
.isUnsigned
;
4082 Diag(Tok
.getLocation(),
4083 diag::ext_integer_literal_too_large_for_signed
);
4084 Ty
= Context
.UnsignedLongLongTy
;
4085 Width
= Context
.getTargetInfo().getLongLongWidth();
4088 if (ResultVal
.getBitWidth() != Width
)
4089 ResultVal
= ResultVal
.trunc(Width
);
4091 Res
= IntegerLiteral::Create(Context
, ResultVal
, Ty
, Tok
.getLocation());
4094 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4095 if (Literal
.isImaginary
) {
4096 Res
= new (Context
) ImaginaryLiteral(Res
,
4097 Context
.getComplexType(Res
->getType()));
4099 // In C++, this is a GNU extension. In C, it's a C2y extension.
4101 if (getLangOpts().CPlusPlus
)
4102 DiagId
= diag::ext_gnu_imaginary_constant
;
4103 else if (getLangOpts().C2y
)
4104 DiagId
= diag::warn_c23_compat_imaginary_constant
;
4106 DiagId
= diag::ext_c2y_imaginary_constant
;
4107 Diag(Tok
.getLocation(), DiagId
);
4112 ExprResult
Sema::ActOnParenExpr(SourceLocation L
, SourceLocation R
, Expr
*E
) {
4113 assert(E
&& "ActOnParenExpr() missing expr");
4114 QualType ExprTy
= E
->getType();
4115 if (getLangOpts().ProtectParens
&& CurFPFeatures
.getAllowFPReassociate() &&
4116 !E
->isLValue() && ExprTy
->hasFloatingRepresentation())
4117 return BuildBuiltinCallExpr(R
, Builtin::BI__arithmetic_fence
, E
);
4118 return new (Context
) ParenExpr(L
, R
, E
);
4121 static bool CheckVecStepTraitOperandType(Sema
&S
, QualType T
,
4123 SourceRange ArgRange
) {
4124 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4125 // scalar or vector data type argument..."
4126 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4127 // type (C99 6.2.5p18) or void.
4128 if (!(T
->isArithmeticType() || T
->isVoidType() || T
->isVectorType())) {
4129 S
.Diag(Loc
, diag::err_vecstep_non_scalar_vector_type
)
4134 assert((T
->isVoidType() || !T
->isIncompleteType()) &&
4135 "Scalar types should always be complete");
4139 static bool CheckVectorElementsTraitOperandType(Sema
&S
, QualType T
,
4141 SourceRange ArgRange
) {
4142 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4143 if (!T
->isVectorType() && !T
->isSizelessVectorType())
4144 return S
.Diag(Loc
, diag::err_builtin_non_vector_type
)
4146 << "__builtin_vectorelements" << T
<< ArgRange
;
4151 static bool checkPtrAuthTypeDiscriminatorOperandType(Sema
&S
, QualType T
,
4153 SourceRange ArgRange
) {
4154 if (S
.checkPointerAuthEnabled(Loc
, ArgRange
))
4157 if (!T
->isFunctionType() && !T
->isFunctionPointerType() &&
4158 !T
->isFunctionReferenceType() && !T
->isMemberFunctionPointerType()) {
4159 S
.Diag(Loc
, diag::err_ptrauth_type_disc_undiscriminated
) << T
<< ArgRange
;
4166 static bool CheckExtensionTraitOperandType(Sema
&S
, QualType T
,
4168 SourceRange ArgRange
,
4169 UnaryExprOrTypeTrait TraitKind
) {
4170 // Invalid types must be hard errors for SFINAE in C++.
4171 if (S
.LangOpts
.CPlusPlus
)
4175 if (T
->isFunctionType() &&
4176 (TraitKind
== UETT_SizeOf
|| TraitKind
== UETT_AlignOf
||
4177 TraitKind
== UETT_PreferredAlignOf
)) {
4178 // sizeof(function)/alignof(function) is allowed as an extension.
4179 S
.Diag(Loc
, diag::ext_sizeof_alignof_function_type
)
4180 << getTraitSpelling(TraitKind
) << ArgRange
;
4184 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4185 // this is an error (OpenCL v1.1 s6.3.k)
4186 if (T
->isVoidType()) {
4187 unsigned DiagID
= S
.LangOpts
.OpenCL
? diag::err_opencl_sizeof_alignof_type
4188 : diag::ext_sizeof_alignof_void_type
;
4189 S
.Diag(Loc
, DiagID
) << getTraitSpelling(TraitKind
) << ArgRange
;
4196 static bool CheckObjCTraitOperandConstraints(Sema
&S
, QualType T
,
4198 SourceRange ArgRange
,
4199 UnaryExprOrTypeTrait TraitKind
) {
4200 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4201 // runtime doesn't allow it.
4202 if (!S
.LangOpts
.ObjCRuntime
.allowsSizeofAlignof() && T
->isObjCObjectType()) {
4203 S
.Diag(Loc
, diag::err_sizeof_nonfragile_interface
)
4204 << T
<< (TraitKind
== UETT_SizeOf
)
4212 /// Check whether E is a pointer from a decayed array type (the decayed
4213 /// pointer type is equal to T) and emit a warning if it is.
4214 static void warnOnSizeofOnArrayDecay(Sema
&S
, SourceLocation Loc
, QualType T
,
4216 // Don't warn if the operation changed the type.
4217 if (T
!= E
->getType())
4220 // Now look for array decays.
4221 const auto *ICE
= dyn_cast
<ImplicitCastExpr
>(E
);
4222 if (!ICE
|| ICE
->getCastKind() != CK_ArrayToPointerDecay
)
4225 S
.Diag(Loc
, diag::warn_sizeof_array_decay
) << ICE
->getSourceRange()
4227 << ICE
->getSubExpr()->getType();
4230 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr
*E
,
4231 UnaryExprOrTypeTrait ExprKind
) {
4232 QualType ExprTy
= E
->getType();
4233 assert(!ExprTy
->isReferenceType());
4235 bool IsUnevaluatedOperand
=
4236 (ExprKind
== UETT_SizeOf
|| ExprKind
== UETT_DataSizeOf
||
4237 ExprKind
== UETT_AlignOf
|| ExprKind
== UETT_PreferredAlignOf
||
4238 ExprKind
== UETT_VecStep
);
4239 if (IsUnevaluatedOperand
) {
4240 ExprResult Result
= CheckUnevaluatedOperand(E
);
4241 if (Result
.isInvalid())
4246 // The operand for sizeof and alignof is in an unevaluated expression context,
4247 // so side effects could result in unintended consequences.
4248 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4249 // used to build SFINAE gadgets.
4250 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4251 if (IsUnevaluatedOperand
&& !inTemplateInstantiation() &&
4252 !E
->isInstantiationDependent() &&
4253 !E
->getType()->isVariableArrayType() &&
4254 E
->HasSideEffects(Context
, false))
4255 Diag(E
->getExprLoc(), diag::warn_side_effects_unevaluated_context
);
4257 if (ExprKind
== UETT_VecStep
)
4258 return CheckVecStepTraitOperandType(*this, ExprTy
, E
->getExprLoc(),
4259 E
->getSourceRange());
4261 if (ExprKind
== UETT_VectorElements
)
4262 return CheckVectorElementsTraitOperandType(*this, ExprTy
, E
->getExprLoc(),
4263 E
->getSourceRange());
4265 // Explicitly list some types as extensions.
4266 if (!CheckExtensionTraitOperandType(*this, ExprTy
, E
->getExprLoc(),
4267 E
->getSourceRange(), ExprKind
))
4270 // WebAssembly tables are always illegal operands to unary expressions and
4272 if (Context
.getTargetInfo().getTriple().isWasm() &&
4273 E
->getType()->isWebAssemblyTableType()) {
4274 Diag(E
->getExprLoc(), diag::err_wasm_table_invalid_uett_operand
)
4275 << getTraitSpelling(ExprKind
);
4279 // 'alignof' applied to an expression only requires the base element type of
4280 // the expression to be complete. 'sizeof' requires the expression's type to
4281 // be complete (and will attempt to complete it if it's an array of unknown
4283 if (ExprKind
== UETT_AlignOf
|| ExprKind
== UETT_PreferredAlignOf
) {
4284 if (RequireCompleteSizedType(
4285 E
->getExprLoc(), Context
.getBaseElementType(E
->getType()),
4286 diag::err_sizeof_alignof_incomplete_or_sizeless_type
,
4287 getTraitSpelling(ExprKind
), E
->getSourceRange()))
4290 if (RequireCompleteSizedExprType(
4291 E
, diag::err_sizeof_alignof_incomplete_or_sizeless_type
,
4292 getTraitSpelling(ExprKind
), E
->getSourceRange()))
4296 // Completing the expression's type may have changed it.
4297 ExprTy
= E
->getType();
4298 assert(!ExprTy
->isReferenceType());
4300 if (ExprTy
->isFunctionType()) {
4301 Diag(E
->getExprLoc(), diag::err_sizeof_alignof_function_type
)
4302 << getTraitSpelling(ExprKind
) << E
->getSourceRange();
4306 if (CheckObjCTraitOperandConstraints(*this, ExprTy
, E
->getExprLoc(),
4307 E
->getSourceRange(), ExprKind
))
4310 if (ExprKind
== UETT_SizeOf
) {
4311 if (const auto *DeclRef
= dyn_cast
<DeclRefExpr
>(E
->IgnoreParens())) {
4312 if (const auto *PVD
= dyn_cast
<ParmVarDecl
>(DeclRef
->getFoundDecl())) {
4313 QualType OType
= PVD
->getOriginalType();
4314 QualType Type
= PVD
->getType();
4315 if (Type
->isPointerType() && OType
->isArrayType()) {
4316 Diag(E
->getExprLoc(), diag::warn_sizeof_array_param
)
4318 Diag(PVD
->getLocation(), diag::note_declared_at
);
4323 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4324 // decays into a pointer and returns an unintended result. This is most
4325 // likely a typo for "sizeof(array) op x".
4326 if (const auto *BO
= dyn_cast
<BinaryOperator
>(E
->IgnoreParens())) {
4327 warnOnSizeofOnArrayDecay(*this, BO
->getOperatorLoc(), BO
->getType(),
4329 warnOnSizeofOnArrayDecay(*this, BO
->getOperatorLoc(), BO
->getType(),
4337 static bool CheckAlignOfExpr(Sema
&S
, Expr
*E
, UnaryExprOrTypeTrait ExprKind
) {
4338 // Cannot know anything else if the expression is dependent.
4339 if (E
->isTypeDependent())
4342 if (E
->getObjectKind() == OK_BitField
) {
4343 S
.Diag(E
->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield
)
4344 << 1 << E
->getSourceRange();
4348 ValueDecl
*D
= nullptr;
4349 Expr
*Inner
= E
->IgnoreParens();
4350 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(Inner
)) {
4352 } else if (MemberExpr
*ME
= dyn_cast
<MemberExpr
>(Inner
)) {
4353 D
= ME
->getMemberDecl();
4356 // If it's a field, require the containing struct to have a
4357 // complete definition so that we can compute the layout.
4359 // This can happen in C++11 onwards, either by naming the member
4360 // in a way that is not transformed into a member access expression
4361 // (in an unevaluated operand, for instance), or by naming the member
4362 // in a trailing-return-type.
4364 // For the record, since __alignof__ on expressions is a GCC
4365 // extension, GCC seems to permit this but always gives the
4366 // nonsensical answer 0.
4368 // We don't really need the layout here --- we could instead just
4369 // directly check for all the appropriate alignment-lowing
4370 // attributes --- but that would require duplicating a lot of
4371 // logic that just isn't worth duplicating for such a marginal
4373 if (FieldDecl
*FD
= dyn_cast_or_null
<FieldDecl
>(D
)) {
4374 // Fast path this check, since we at least know the record has a
4375 // definition if we can find a member of it.
4376 if (!FD
->getParent()->isCompleteDefinition()) {
4377 S
.Diag(E
->getExprLoc(), diag::err_alignof_member_of_incomplete_type
)
4378 << E
->getSourceRange();
4382 // Otherwise, if it's a field, and the field doesn't have
4383 // reference type, then it must have a complete type (or be a
4384 // flexible array member, which we explicitly want to
4385 // white-list anyway), which makes the following checks trivial.
4386 if (!FD
->getType()->isReferenceType())
4390 return S
.CheckUnaryExprOrTypeTraitOperand(E
, ExprKind
);
4393 bool Sema::CheckVecStepExpr(Expr
*E
) {
4394 E
= E
->IgnoreParens();
4396 // Cannot know anything else if the expression is dependent.
4397 if (E
->isTypeDependent())
4400 return CheckUnaryExprOrTypeTraitOperand(E
, UETT_VecStep
);
4403 static void captureVariablyModifiedType(ASTContext
&Context
, QualType T
,
4404 CapturingScopeInfo
*CSI
) {
4405 assert(T
->isVariablyModifiedType());
4406 assert(CSI
!= nullptr);
4408 // We're going to walk down into the type and look for VLA expressions.
4410 const Type
*Ty
= T
.getTypePtr();
4411 switch (Ty
->getTypeClass()) {
4412 #define TYPE(Class, Base)
4413 #define ABSTRACT_TYPE(Class, Base)
4414 #define NON_CANONICAL_TYPE(Class, Base)
4415 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4416 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4417 #include "clang/AST/TypeNodes.inc"
4420 // These types are never variably-modified.
4424 case Type::ExtVector
:
4425 case Type::ConstantMatrix
:
4428 case Type::TemplateSpecialization
:
4429 case Type::ObjCObject
:
4430 case Type::ObjCInterface
:
4431 case Type::ObjCObjectPointer
:
4432 case Type::ObjCTypeParam
:
4435 llvm_unreachable("type class is never variably-modified!");
4436 case Type::Elaborated
:
4437 T
= cast
<ElaboratedType
>(Ty
)->getNamedType();
4439 case Type::Adjusted
:
4440 T
= cast
<AdjustedType
>(Ty
)->getOriginalType();
4443 T
= cast
<DecayedType
>(Ty
)->getPointeeType();
4445 case Type::ArrayParameter
:
4446 T
= cast
<ArrayParameterType
>(Ty
)->getElementType();
4449 T
= cast
<PointerType
>(Ty
)->getPointeeType();
4451 case Type::BlockPointer
:
4452 T
= cast
<BlockPointerType
>(Ty
)->getPointeeType();
4454 case Type::LValueReference
:
4455 case Type::RValueReference
:
4456 T
= cast
<ReferenceType
>(Ty
)->getPointeeType();
4458 case Type::MemberPointer
:
4459 T
= cast
<MemberPointerType
>(Ty
)->getPointeeType();
4461 case Type::ConstantArray
:
4462 case Type::IncompleteArray
:
4463 // Losing element qualification here is fine.
4464 T
= cast
<ArrayType
>(Ty
)->getElementType();
4466 case Type::VariableArray
: {
4467 // Losing element qualification here is fine.
4468 const VariableArrayType
*VAT
= cast
<VariableArrayType
>(Ty
);
4470 // Unknown size indication requires no size computation.
4471 // Otherwise, evaluate and record it.
4472 auto Size
= VAT
->getSizeExpr();
4473 if (Size
&& !CSI
->isVLATypeCaptured(VAT
) &&
4474 (isa
<CapturedRegionScopeInfo
>(CSI
) || isa
<LambdaScopeInfo
>(CSI
)))
4475 CSI
->addVLATypeCapture(Size
->getExprLoc(), VAT
, Context
.getSizeType());
4477 T
= VAT
->getElementType();
4480 case Type::FunctionProto
:
4481 case Type::FunctionNoProto
:
4482 T
= cast
<FunctionType
>(Ty
)->getReturnType();
4486 case Type::UnaryTransform
:
4487 case Type::Attributed
:
4488 case Type::BTFTagAttributed
:
4489 case Type::HLSLAttributedResource
:
4490 case Type::SubstTemplateTypeParm
:
4491 case Type::MacroQualified
:
4492 case Type::CountAttributed
:
4493 // Keep walking after single level desugaring.
4494 T
= T
.getSingleStepDesugaredType(Context
);
4497 T
= cast
<TypedefType
>(Ty
)->desugar();
4499 case Type::Decltype
:
4500 T
= cast
<DecltypeType
>(Ty
)->desugar();
4502 case Type::PackIndexing
:
4503 T
= cast
<PackIndexingType
>(Ty
)->desugar();
4506 T
= cast
<UsingType
>(Ty
)->desugar();
4509 case Type::DeducedTemplateSpecialization
:
4510 T
= cast
<DeducedType
>(Ty
)->getDeducedType();
4512 case Type::TypeOfExpr
:
4513 T
= cast
<TypeOfExprType
>(Ty
)->getUnderlyingExpr()->getType();
4516 T
= cast
<AtomicType
>(Ty
)->getValueType();
4519 } while (!T
.isNull() && T
->isVariablyModifiedType());
4522 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType
,
4523 SourceLocation OpLoc
,
4524 SourceRange ExprRange
,
4525 UnaryExprOrTypeTrait ExprKind
,
4527 if (ExprType
->isDependentType())
4530 // C++ [expr.sizeof]p2:
4531 // When applied to a reference or a reference type, the result
4532 // is the size of the referenced type.
4533 // C++11 [expr.alignof]p3:
4534 // When alignof is applied to a reference type, the result
4535 // shall be the alignment of the referenced type.
4536 if (const ReferenceType
*Ref
= ExprType
->getAs
<ReferenceType
>())
4537 ExprType
= Ref
->getPointeeType();
4539 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4540 // When alignof or _Alignof is applied to an array type, the result
4541 // is the alignment of the element type.
4542 if (ExprKind
== UETT_AlignOf
|| ExprKind
== UETT_PreferredAlignOf
||
4543 ExprKind
== UETT_OpenMPRequiredSimdAlign
) {
4544 // If the trait is 'alignof' in C before C2y, the ability to apply the
4545 // trait to an incomplete array is an extension.
4546 if (ExprKind
== UETT_AlignOf
&& !getLangOpts().CPlusPlus
&&
4547 ExprType
->isIncompleteArrayType())
4548 Diag(OpLoc
, getLangOpts().C2y
4549 ? diag::warn_c2y_compat_alignof_incomplete_array
4550 : diag::ext_c2y_alignof_incomplete_array
);
4551 ExprType
= Context
.getBaseElementType(ExprType
);
4554 if (ExprKind
== UETT_VecStep
)
4555 return CheckVecStepTraitOperandType(*this, ExprType
, OpLoc
, ExprRange
);
4557 if (ExprKind
== UETT_VectorElements
)
4558 return CheckVectorElementsTraitOperandType(*this, ExprType
, OpLoc
,
4561 if (ExprKind
== UETT_PtrAuthTypeDiscriminator
)
4562 return checkPtrAuthTypeDiscriminatorOperandType(*this, ExprType
, OpLoc
,
4565 // Explicitly list some types as extensions.
4566 if (!CheckExtensionTraitOperandType(*this, ExprType
, OpLoc
, ExprRange
,
4570 if (RequireCompleteSizedType(
4571 OpLoc
, ExprType
, diag::err_sizeof_alignof_incomplete_or_sizeless_type
,
4575 if (ExprType
->isFunctionType()) {
4576 Diag(OpLoc
, diag::err_sizeof_alignof_function_type
) << KWName
<< ExprRange
;
4580 // WebAssembly tables are always illegal operands to unary expressions and
4582 if (Context
.getTargetInfo().getTriple().isWasm() &&
4583 ExprType
->isWebAssemblyTableType()) {
4584 Diag(OpLoc
, diag::err_wasm_table_invalid_uett_operand
)
4585 << getTraitSpelling(ExprKind
);
4589 if (CheckObjCTraitOperandConstraints(*this, ExprType
, OpLoc
, ExprRange
,
4593 if (ExprType
->isVariablyModifiedType() && FunctionScopes
.size() > 1) {
4594 if (auto *TT
= ExprType
->getAs
<TypedefType
>()) {
4595 for (auto I
= FunctionScopes
.rbegin(),
4596 E
= std::prev(FunctionScopes
.rend());
4598 auto *CSI
= dyn_cast
<CapturingScopeInfo
>(*I
);
4601 DeclContext
*DC
= nullptr;
4602 if (auto *LSI
= dyn_cast
<LambdaScopeInfo
>(CSI
))
4603 DC
= LSI
->CallOperator
;
4604 else if (auto *CRSI
= dyn_cast
<CapturedRegionScopeInfo
>(CSI
))
4605 DC
= CRSI
->TheCapturedDecl
;
4606 else if (auto *BSI
= dyn_cast
<BlockScopeInfo
>(CSI
))
4609 if (DC
->containsDecl(TT
->getDecl()))
4611 captureVariablyModifiedType(Context
, ExprType
, CSI
);
4620 ExprResult
Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo
*TInfo
,
4621 SourceLocation OpLoc
,
4622 UnaryExprOrTypeTrait ExprKind
,
4627 QualType T
= TInfo
->getType();
4629 if (!T
->isDependentType() &&
4630 CheckUnaryExprOrTypeTraitOperand(T
, OpLoc
, R
, ExprKind
,
4631 getTraitSpelling(ExprKind
)))
4634 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4635 // properly deal with VLAs in nested calls of sizeof and typeof.
4636 if (isUnevaluatedContext() && ExprKind
== UETT_SizeOf
&&
4637 TInfo
->getType()->isVariablyModifiedType())
4638 TInfo
= TransformToPotentiallyEvaluated(TInfo
);
4640 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4641 return new (Context
) UnaryExprOrTypeTraitExpr(
4642 ExprKind
, TInfo
, Context
.getSizeType(), OpLoc
, R
.getEnd());
4646 Sema::CreateUnaryExprOrTypeTraitExpr(Expr
*E
, SourceLocation OpLoc
,
4647 UnaryExprOrTypeTrait ExprKind
) {
4648 ExprResult PE
= CheckPlaceholderExpr(E
);
4654 // Verify that the operand is valid.
4655 bool isInvalid
= false;
4656 if (E
->isTypeDependent()) {
4657 // Delay type-checking for type-dependent expressions.
4658 } else if (ExprKind
== UETT_AlignOf
|| ExprKind
== UETT_PreferredAlignOf
) {
4659 isInvalid
= CheckAlignOfExpr(*this, E
, ExprKind
);
4660 } else if (ExprKind
== UETT_VecStep
) {
4661 isInvalid
= CheckVecStepExpr(E
);
4662 } else if (ExprKind
== UETT_OpenMPRequiredSimdAlign
) {
4663 Diag(E
->getExprLoc(), diag::err_openmp_default_simd_align_expr
);
4665 } else if (E
->refersToBitField()) { // C99 6.5.3.4p1.
4666 Diag(E
->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield
) << 0;
4668 } else if (ExprKind
== UETT_VectorElements
) {
4669 isInvalid
= CheckUnaryExprOrTypeTraitOperand(E
, UETT_VectorElements
);
4671 isInvalid
= CheckUnaryExprOrTypeTraitOperand(E
, UETT_SizeOf
);
4677 if (ExprKind
== UETT_SizeOf
&& E
->getType()->isVariableArrayType()) {
4678 PE
= TransformToPotentiallyEvaluated(E
);
4679 if (PE
.isInvalid()) return ExprError();
4683 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4684 return new (Context
) UnaryExprOrTypeTraitExpr(
4685 ExprKind
, E
, Context
.getSizeType(), OpLoc
, E
->getSourceRange().getEnd());
4689 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc
,
4690 UnaryExprOrTypeTrait ExprKind
, bool IsType
,
4691 void *TyOrEx
, SourceRange ArgRange
) {
4692 // If error parsing type, ignore.
4693 if (!TyOrEx
) return ExprError();
4696 TypeSourceInfo
*TInfo
;
4697 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx
), &TInfo
);
4698 return CreateUnaryExprOrTypeTraitExpr(TInfo
, OpLoc
, ExprKind
, ArgRange
);
4701 Expr
*ArgEx
= (Expr
*)TyOrEx
;
4702 ExprResult Result
= CreateUnaryExprOrTypeTraitExpr(ArgEx
, OpLoc
, ExprKind
);
4706 bool Sema::CheckAlignasTypeArgument(StringRef KWName
, TypeSourceInfo
*TInfo
,
4707 SourceLocation OpLoc
, SourceRange R
) {
4710 return CheckUnaryExprOrTypeTraitOperand(TInfo
->getType(), OpLoc
, R
,
4711 UETT_AlignOf
, KWName
);
4714 bool Sema::ActOnAlignasTypeArgument(StringRef KWName
, ParsedType Ty
,
4715 SourceLocation OpLoc
, SourceRange R
) {
4716 TypeSourceInfo
*TInfo
;
4717 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(Ty
.getAsOpaquePtr()),
4719 return CheckAlignasTypeArgument(KWName
, TInfo
, OpLoc
, R
);
4722 static QualType
CheckRealImagOperand(Sema
&S
, ExprResult
&V
, SourceLocation Loc
,
4724 if (V
.get()->isTypeDependent())
4725 return S
.Context
.DependentTy
;
4727 // _Real and _Imag are only l-values for normal l-values.
4728 if (V
.get()->getObjectKind() != OK_Ordinary
) {
4729 V
= S
.DefaultLvalueConversion(V
.get());
4734 // These operators return the element type of a complex type.
4735 if (const ComplexType
*CT
= V
.get()->getType()->getAs
<ComplexType
>())
4736 return CT
->getElementType();
4738 // Otherwise they pass through real integer and floating point types here.
4739 if (V
.get()->getType()->isArithmeticType())
4740 return V
.get()->getType();
4742 // Test for placeholders.
4743 ExprResult PR
= S
.CheckPlaceholderExpr(V
.get());
4744 if (PR
.isInvalid()) return QualType();
4745 if (PR
.get() != V
.get()) {
4747 return CheckRealImagOperand(S
, V
, Loc
, IsReal
);
4750 // Reject anything else.
4751 S
.Diag(Loc
, diag::err_realimag_invalid_type
) << V
.get()->getType()
4752 << (IsReal
? "__real" : "__imag");
4759 Sema::ActOnPostfixUnaryOp(Scope
*S
, SourceLocation OpLoc
,
4760 tok::TokenKind Kind
, Expr
*Input
) {
4761 UnaryOperatorKind Opc
;
4763 default: llvm_unreachable("Unknown unary op!");
4764 case tok::plusplus
: Opc
= UO_PostInc
; break;
4765 case tok::minusminus
: Opc
= UO_PostDec
; break;
4768 // Since this might is a postfix expression, get rid of ParenListExprs.
4769 ExprResult Result
= MaybeConvertParenListExprToParenExpr(S
, Input
);
4770 if (Result
.isInvalid()) return ExprError();
4771 Input
= Result
.get();
4773 return BuildUnaryOp(S
, OpLoc
, Opc
, Input
);
4776 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4778 /// \return true on error
4779 static bool checkArithmeticOnObjCPointer(Sema
&S
,
4780 SourceLocation opLoc
,
4782 assert(op
->getType()->isObjCObjectPointerType());
4783 if (S
.LangOpts
.ObjCRuntime
.allowsPointerArithmetic() &&
4784 !S
.LangOpts
.ObjCSubscriptingLegacyRuntime
)
4787 S
.Diag(opLoc
, diag::err_arithmetic_nonfragile_interface
)
4788 << op
->getType()->castAs
<ObjCObjectPointerType
>()->getPointeeType()
4789 << op
->getSourceRange();
4793 static bool isMSPropertySubscriptExpr(Sema
&S
, Expr
*Base
) {
4794 auto *BaseNoParens
= Base
->IgnoreParens();
4795 if (auto *MSProp
= dyn_cast
<MSPropertyRefExpr
>(BaseNoParens
))
4796 return MSProp
->getPropertyDecl()->getType()->isArrayType();
4797 return isa
<MSPropertySubscriptExpr
>(BaseNoParens
);
4800 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4801 // Typically this is DependentTy, but can sometimes be more precise.
4803 // There are cases when we could determine a non-dependent type:
4804 // - LHS and RHS may have non-dependent types despite being type-dependent
4805 // (e.g. unbounded array static members of the current instantiation)
4806 // - one may be a dependent-sized array with known element type
4807 // - one may be a dependent-typed valid index (enum in current instantiation)
4809 // We *always* return a dependent type, in such cases it is DependentTy.
4810 // This avoids creating type-dependent expressions with non-dependent types.
4811 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4812 static QualType
getDependentArraySubscriptType(Expr
*LHS
, Expr
*RHS
,
4813 const ASTContext
&Ctx
) {
4814 assert(LHS
->isTypeDependent() || RHS
->isTypeDependent());
4815 QualType LTy
= LHS
->getType(), RTy
= RHS
->getType();
4816 QualType Result
= Ctx
.DependentTy
;
4817 if (RTy
->isIntegralOrUnscopedEnumerationType()) {
4818 if (const PointerType
*PT
= LTy
->getAs
<PointerType
>())
4819 Result
= PT
->getPointeeType();
4820 else if (const ArrayType
*AT
= LTy
->getAsArrayTypeUnsafe())
4821 Result
= AT
->getElementType();
4822 } else if (LTy
->isIntegralOrUnscopedEnumerationType()) {
4823 if (const PointerType
*PT
= RTy
->getAs
<PointerType
>())
4824 Result
= PT
->getPointeeType();
4825 else if (const ArrayType
*AT
= RTy
->getAsArrayTypeUnsafe())
4826 Result
= AT
->getElementType();
4828 // Ensure we return a dependent type.
4829 return Result
->isDependentType() ? Result
: Ctx
.DependentTy
;
4832 ExprResult
Sema::ActOnArraySubscriptExpr(Scope
*S
, Expr
*base
,
4833 SourceLocation lbLoc
,
4834 MultiExprArg ArgExprs
,
4835 SourceLocation rbLoc
) {
4837 if (base
&& !base
->getType().isNull() &&
4838 base
->hasPlaceholderType(BuiltinType::ArraySection
)) {
4839 auto *AS
= cast
<ArraySectionExpr
>(base
);
4840 if (AS
->isOMPArraySection())
4841 return OpenMP().ActOnOMPArraySectionExpr(
4842 base
, lbLoc
, ArgExprs
.front(), SourceLocation(), SourceLocation(),
4844 /*Stride=*/nullptr, rbLoc
);
4846 return OpenACC().ActOnArraySectionExpr(base
, lbLoc
, ArgExprs
.front(),
4847 SourceLocation(), /*Length*/ nullptr,
4851 // Since this might be a postfix expression, get rid of ParenListExprs.
4852 if (isa
<ParenListExpr
>(base
)) {
4853 ExprResult result
= MaybeConvertParenListExprToParenExpr(S
, base
);
4854 if (result
.isInvalid())
4856 base
= result
.get();
4859 // Check if base and idx form a MatrixSubscriptExpr.
4861 // Helper to check for comma expressions, which are not allowed as indices for
4862 // matrix subscript expressions.
4863 auto CheckAndReportCommaError
= [this, base
, rbLoc
](Expr
*E
) {
4864 if (isa
<BinaryOperator
>(E
) && cast
<BinaryOperator
>(E
)->isCommaOp()) {
4865 Diag(E
->getExprLoc(), diag::err_matrix_subscript_comma
)
4866 << SourceRange(base
->getBeginLoc(), rbLoc
);
4871 // The matrix subscript operator ([][])is considered a single operator.
4872 // Separating the index expressions by parenthesis is not allowed.
4873 if (base
&& !base
->getType().isNull() &&
4874 base
->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx
) &&
4875 !isa
<MatrixSubscriptExpr
>(base
)) {
4876 Diag(base
->getExprLoc(), diag::err_matrix_separate_incomplete_index
)
4877 << SourceRange(base
->getBeginLoc(), rbLoc
);
4880 // If the base is a MatrixSubscriptExpr, try to create a new
4881 // MatrixSubscriptExpr.
4882 auto *matSubscriptE
= dyn_cast
<MatrixSubscriptExpr
>(base
);
4883 if (matSubscriptE
) {
4884 assert(ArgExprs
.size() == 1);
4885 if (CheckAndReportCommaError(ArgExprs
.front()))
4888 assert(matSubscriptE
->isIncomplete() &&
4889 "base has to be an incomplete matrix subscript");
4890 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE
->getBase(),
4891 matSubscriptE
->getRowIdx(),
4892 ArgExprs
.front(), rbLoc
);
4894 if (base
->getType()->isWebAssemblyTableType()) {
4895 Diag(base
->getExprLoc(), diag::err_wasm_table_art
)
4896 << SourceRange(base
->getBeginLoc(), rbLoc
) << 3;
4900 CheckInvalidBuiltinCountedByRef(base
, ArraySubscriptKind
);
4902 // Handle any non-overload placeholder types in the base and index
4903 // expressions. We can't handle overloads here because the other
4904 // operand might be an overloadable type, in which case the overload
4905 // resolution for the operator overload should get the first crack
4907 bool IsMSPropertySubscript
= false;
4908 if (base
->getType()->isNonOverloadPlaceholderType()) {
4909 IsMSPropertySubscript
= isMSPropertySubscriptExpr(*this, base
);
4910 if (!IsMSPropertySubscript
) {
4911 ExprResult result
= CheckPlaceholderExpr(base
);
4912 if (result
.isInvalid())
4914 base
= result
.get();
4918 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4919 if (base
->getType()->isMatrixType()) {
4920 assert(ArgExprs
.size() == 1);
4921 if (CheckAndReportCommaError(ArgExprs
.front()))
4924 return CreateBuiltinMatrixSubscriptExpr(base
, ArgExprs
.front(), nullptr,
4928 if (ArgExprs
.size() == 1 && getLangOpts().CPlusPlus20
) {
4929 Expr
*idx
= ArgExprs
[0];
4930 if ((isa
<BinaryOperator
>(idx
) && cast
<BinaryOperator
>(idx
)->isCommaOp()) ||
4931 (isa
<CXXOperatorCallExpr
>(idx
) &&
4932 cast
<CXXOperatorCallExpr
>(idx
)->getOperator() == OO_Comma
)) {
4933 Diag(idx
->getExprLoc(), diag::warn_deprecated_comma_subscript
)
4934 << SourceRange(base
->getBeginLoc(), rbLoc
);
4938 if (ArgExprs
.size() == 1 &&
4939 ArgExprs
[0]->getType()->isNonOverloadPlaceholderType()) {
4940 ExprResult result
= CheckPlaceholderExpr(ArgExprs
[0]);
4941 if (result
.isInvalid())
4943 ArgExprs
[0] = result
.get();
4945 if (CheckArgsForPlaceholders(ArgExprs
))
4949 // Build an unanalyzed expression if either operand is type-dependent.
4950 if (getLangOpts().CPlusPlus
&& ArgExprs
.size() == 1 &&
4951 (base
->isTypeDependent() ||
4952 Expr::hasAnyTypeDependentArguments(ArgExprs
)) &&
4953 !isa
<PackExpansionExpr
>(ArgExprs
[0])) {
4954 return new (Context
) ArraySubscriptExpr(
4955 base
, ArgExprs
.front(),
4956 getDependentArraySubscriptType(base
, ArgExprs
.front(), getASTContext()),
4957 VK_LValue
, OK_Ordinary
, rbLoc
);
4960 // MSDN, property (C++)
4961 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4962 // This attribute can also be used in the declaration of an empty array in a
4963 // class or structure definition. For example:
4964 // __declspec(property(get=GetX, put=PutX)) int x[];
4965 // The above statement indicates that x[] can be used with one or more array
4966 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4967 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4968 if (IsMSPropertySubscript
) {
4969 assert(ArgExprs
.size() == 1);
4970 // Build MS property subscript expression if base is MS property reference
4971 // or MS property subscript.
4972 return new (Context
)
4973 MSPropertySubscriptExpr(base
, ArgExprs
.front(), Context
.PseudoObjectTy
,
4974 VK_LValue
, OK_Ordinary
, rbLoc
);
4977 // Use C++ overloaded-operator rules if either operand has record
4978 // type. The spec says to do this if either type is *overloadable*,
4979 // but enum types can't declare subscript operators or conversion
4980 // operators, so there's nothing interesting for overload resolution
4981 // to do if there aren't any record types involved.
4983 // ObjC pointers have their own subscripting logic that is not tied
4984 // to overload resolution and so should not take this path.
4985 if (getLangOpts().CPlusPlus
&& !base
->getType()->isObjCObjectPointerType() &&
4986 ((base
->getType()->isRecordType() ||
4987 (ArgExprs
.size() != 1 || isa
<PackExpansionExpr
>(ArgExprs
[0]) ||
4988 ArgExprs
[0]->getType()->isRecordType())))) {
4989 return CreateOverloadedArraySubscriptExpr(lbLoc
, rbLoc
, base
, ArgExprs
);
4993 CreateBuiltinArraySubscriptExpr(base
, lbLoc
, ArgExprs
.front(), rbLoc
);
4995 if (!Res
.isInvalid() && isa
<ArraySubscriptExpr
>(Res
.get()))
4996 CheckSubscriptAccessOfNoDeref(cast
<ArraySubscriptExpr
>(Res
.get()));
5001 ExprResult
Sema::tryConvertExprToType(Expr
*E
, QualType Ty
) {
5002 InitializedEntity Entity
= InitializedEntity::InitializeTemporary(Ty
);
5003 InitializationKind Kind
=
5004 InitializationKind::CreateCopy(E
->getBeginLoc(), SourceLocation());
5005 InitializationSequence
InitSeq(*this, Entity
, Kind
, E
);
5006 return InitSeq
.Perform(*this, Entity
, Kind
, E
);
5009 ExprResult
Sema::CreateBuiltinMatrixSubscriptExpr(Expr
*Base
, Expr
*RowIdx
,
5011 SourceLocation RBLoc
) {
5012 ExprResult BaseR
= CheckPlaceholderExpr(Base
);
5013 if (BaseR
.isInvalid())
5017 ExprResult RowR
= CheckPlaceholderExpr(RowIdx
);
5018 if (RowR
.isInvalid())
5020 RowIdx
= RowR
.get();
5023 return new (Context
) MatrixSubscriptExpr(
5024 Base
, RowIdx
, ColumnIdx
, Context
.IncompleteMatrixIdxTy
, RBLoc
);
5026 // Build an unanalyzed expression if any of the operands is type-dependent.
5027 if (Base
->isTypeDependent() || RowIdx
->isTypeDependent() ||
5028 ColumnIdx
->isTypeDependent())
5029 return new (Context
) MatrixSubscriptExpr(Base
, RowIdx
, ColumnIdx
,
5030 Context
.DependentTy
, RBLoc
);
5032 ExprResult ColumnR
= CheckPlaceholderExpr(ColumnIdx
);
5033 if (ColumnR
.isInvalid())
5035 ColumnIdx
= ColumnR
.get();
5037 // Check that IndexExpr is an integer expression. If it is a constant
5038 // expression, check that it is less than Dim (= the number of elements in the
5039 // corresponding dimension).
5040 auto IsIndexValid
= [&](Expr
*IndexExpr
, unsigned Dim
,
5041 bool IsColumnIdx
) -> Expr
* {
5042 if (!IndexExpr
->getType()->isIntegerType() &&
5043 !IndexExpr
->isTypeDependent()) {
5044 Diag(IndexExpr
->getBeginLoc(), diag::err_matrix_index_not_integer
)
5049 if (std::optional
<llvm::APSInt
> Idx
=
5050 IndexExpr
->getIntegerConstantExpr(Context
)) {
5051 if ((*Idx
< 0 || *Idx
>= Dim
)) {
5052 Diag(IndexExpr
->getBeginLoc(), diag::err_matrix_index_outside_range
)
5053 << IsColumnIdx
<< Dim
;
5058 ExprResult ConvExpr
= IndexExpr
;
5059 assert(!ConvExpr
.isInvalid() &&
5060 "should be able to convert any integer type to size type");
5061 return ConvExpr
.get();
5064 auto *MTy
= Base
->getType()->getAs
<ConstantMatrixType
>();
5065 RowIdx
= IsIndexValid(RowIdx
, MTy
->getNumRows(), false);
5066 ColumnIdx
= IsIndexValid(ColumnIdx
, MTy
->getNumColumns(), true);
5067 if (!RowIdx
|| !ColumnIdx
)
5070 return new (Context
) MatrixSubscriptExpr(Base
, RowIdx
, ColumnIdx
,
5071 MTy
->getElementType(), RBLoc
);
5074 void Sema::CheckAddressOfNoDeref(const Expr
*E
) {
5075 ExpressionEvaluationContextRecord
&LastRecord
= ExprEvalContexts
.back();
5076 const Expr
*StrippedExpr
= E
->IgnoreParenImpCasts();
5078 // For expressions like `&(*s).b`, the base is recorded and what should be
5080 const MemberExpr
*Member
= nullptr;
5081 while ((Member
= dyn_cast
<MemberExpr
>(StrippedExpr
)) && !Member
->isArrow())
5082 StrippedExpr
= Member
->getBase()->IgnoreParenImpCasts();
5084 LastRecord
.PossibleDerefs
.erase(StrippedExpr
);
5087 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr
*E
) {
5088 if (isUnevaluatedContext())
5091 QualType ResultTy
= E
->getType();
5092 ExpressionEvaluationContextRecord
&LastRecord
= ExprEvalContexts
.back();
5094 // Bail if the element is an array since it is not memory access.
5095 if (isa
<ArrayType
>(ResultTy
))
5098 if (ResultTy
->hasAttr(attr::NoDeref
)) {
5099 LastRecord
.PossibleDerefs
.insert(E
);
5103 // Check if the base type is a pointer to a member access of a struct
5104 // marked with noderef.
5105 const Expr
*Base
= E
->getBase();
5106 QualType BaseTy
= Base
->getType();
5107 if (!(isa
<ArrayType
>(BaseTy
) || isa
<PointerType
>(BaseTy
)))
5108 // Not a pointer access
5111 const MemberExpr
*Member
= nullptr;
5112 while ((Member
= dyn_cast
<MemberExpr
>(Base
->IgnoreParenCasts())) &&
5114 Base
= Member
->getBase();
5116 if (const auto *Ptr
= dyn_cast
<PointerType
>(Base
->getType())) {
5117 if (Ptr
->getPointeeType()->hasAttr(attr::NoDeref
))
5118 LastRecord
.PossibleDerefs
.insert(E
);
5123 Sema::CreateBuiltinArraySubscriptExpr(Expr
*Base
, SourceLocation LLoc
,
5124 Expr
*Idx
, SourceLocation RLoc
) {
5125 Expr
*LHSExp
= Base
;
5128 ExprValueKind VK
= VK_LValue
;
5129 ExprObjectKind OK
= OK_Ordinary
;
5131 // Per C++ core issue 1213, the result is an xvalue if either operand is
5132 // a non-lvalue array, and an lvalue otherwise.
5133 if (getLangOpts().CPlusPlus11
) {
5134 for (auto *Op
: {LHSExp
, RHSExp
}) {
5135 Op
= Op
->IgnoreImplicit();
5136 if (Op
->getType()->isArrayType() && !Op
->isLValue())
5141 // Perform default conversions.
5142 if (!LHSExp
->getType()->isSubscriptableVectorType()) {
5143 ExprResult Result
= DefaultFunctionArrayLvalueConversion(LHSExp
);
5144 if (Result
.isInvalid())
5146 LHSExp
= Result
.get();
5148 ExprResult Result
= DefaultFunctionArrayLvalueConversion(RHSExp
);
5149 if (Result
.isInvalid())
5151 RHSExp
= Result
.get();
5153 QualType LHSTy
= LHSExp
->getType(), RHSTy
= RHSExp
->getType();
5155 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5156 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5157 // in the subscript position. As a result, we need to derive the array base
5158 // and index from the expression types.
5159 Expr
*BaseExpr
, *IndexExpr
;
5160 QualType ResultType
;
5161 if (LHSTy
->isDependentType() || RHSTy
->isDependentType()) {
5165 getDependentArraySubscriptType(LHSExp
, RHSExp
, getASTContext());
5166 } else if (const PointerType
*PTy
= LHSTy
->getAs
<PointerType
>()) {
5169 ResultType
= PTy
->getPointeeType();
5170 } else if (const ObjCObjectPointerType
*PTy
=
5171 LHSTy
->getAs
<ObjCObjectPointerType
>()) {
5175 // Use custom logic if this should be the pseudo-object subscript
5177 if (!LangOpts
.isSubscriptPointerArithmetic())
5178 return ObjC().BuildObjCSubscriptExpression(RLoc
, BaseExpr
, IndexExpr
,
5181 ResultType
= PTy
->getPointeeType();
5182 } else if (const PointerType
*PTy
= RHSTy
->getAs
<PointerType
>()) {
5183 // Handle the uncommon case of "123[Ptr]".
5186 ResultType
= PTy
->getPointeeType();
5187 } else if (const ObjCObjectPointerType
*PTy
=
5188 RHSTy
->getAs
<ObjCObjectPointerType
>()) {
5189 // Handle the uncommon case of "123[Ptr]".
5192 ResultType
= PTy
->getPointeeType();
5193 if (!LangOpts
.isSubscriptPointerArithmetic()) {
5194 Diag(LLoc
, diag::err_subscript_nonfragile_interface
)
5195 << ResultType
<< BaseExpr
->getSourceRange();
5198 } else if (LHSTy
->isSubscriptableVectorType()) {
5199 if (LHSTy
->isBuiltinType() &&
5200 LHSTy
->getAs
<BuiltinType
>()->isSveVLSBuiltinType()) {
5201 const BuiltinType
*BTy
= LHSTy
->getAs
<BuiltinType
>();
5202 if (BTy
->isSVEBool())
5203 return ExprError(Diag(LLoc
, diag::err_subscript_svbool_t
)
5204 << LHSExp
->getSourceRange()
5205 << RHSExp
->getSourceRange());
5206 ResultType
= BTy
->getSveEltType(Context
);
5208 const VectorType
*VTy
= LHSTy
->getAs
<VectorType
>();
5209 ResultType
= VTy
->getElementType();
5211 BaseExpr
= LHSExp
; // vectors: V[123]
5213 // We apply C++ DR1213 to vector subscripting too.
5214 if (getLangOpts().CPlusPlus11
&& LHSExp
->isPRValue()) {
5215 ExprResult Materialized
= TemporaryMaterializationConversion(LHSExp
);
5216 if (Materialized
.isInvalid())
5218 LHSExp
= Materialized
.get();
5220 VK
= LHSExp
->getValueKind();
5221 if (VK
!= VK_PRValue
)
5222 OK
= OK_VectorComponent
;
5224 QualType BaseType
= BaseExpr
->getType();
5225 Qualifiers BaseQuals
= BaseType
.getQualifiers();
5226 Qualifiers MemberQuals
= ResultType
.getQualifiers();
5227 Qualifiers Combined
= BaseQuals
+ MemberQuals
;
5228 if (Combined
!= MemberQuals
)
5229 ResultType
= Context
.getQualifiedType(ResultType
, Combined
);
5230 } else if (LHSTy
->isArrayType()) {
5231 // If we see an array that wasn't promoted by
5232 // DefaultFunctionArrayLvalueConversion, it must be an array that
5233 // wasn't promoted because of the C90 rule that doesn't
5234 // allow promoting non-lvalue arrays. Warn, then
5235 // force the promotion here.
5236 Diag(LHSExp
->getBeginLoc(), diag::ext_subscript_non_lvalue
)
5237 << LHSExp
->getSourceRange();
5238 LHSExp
= ImpCastExprToType(LHSExp
, Context
.getArrayDecayedType(LHSTy
),
5239 CK_ArrayToPointerDecay
).get();
5240 LHSTy
= LHSExp
->getType();
5244 ResultType
= LHSTy
->castAs
<PointerType
>()->getPointeeType();
5245 } else if (RHSTy
->isArrayType()) {
5246 // Same as previous, except for 123[f().a] case
5247 Diag(RHSExp
->getBeginLoc(), diag::ext_subscript_non_lvalue
)
5248 << RHSExp
->getSourceRange();
5249 RHSExp
= ImpCastExprToType(RHSExp
, Context
.getArrayDecayedType(RHSTy
),
5250 CK_ArrayToPointerDecay
).get();
5251 RHSTy
= RHSExp
->getType();
5255 ResultType
= RHSTy
->castAs
<PointerType
>()->getPointeeType();
5257 return ExprError(Diag(LLoc
, diag::err_typecheck_subscript_value
)
5258 << LHSExp
->getSourceRange() << RHSExp
->getSourceRange());
5261 if (!IndexExpr
->getType()->isIntegerType() && !IndexExpr
->isTypeDependent())
5262 return ExprError(Diag(LLoc
, diag::err_typecheck_subscript_not_integer
)
5263 << IndexExpr
->getSourceRange());
5265 if ((IndexExpr
->getType()->isSpecificBuiltinType(BuiltinType::Char_S
) ||
5266 IndexExpr
->getType()->isSpecificBuiltinType(BuiltinType::Char_U
)) &&
5267 !IndexExpr
->isTypeDependent()) {
5268 std::optional
<llvm::APSInt
> IntegerContantExpr
=
5269 IndexExpr
->getIntegerConstantExpr(getASTContext());
5270 if (!IntegerContantExpr
.has_value() ||
5271 IntegerContantExpr
.value().isNegative())
5272 Diag(LLoc
, diag::warn_subscript_is_char
) << IndexExpr
->getSourceRange();
5275 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5276 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5277 // type. Note that Functions are not objects, and that (in C99 parlance)
5278 // incomplete types are not object types.
5279 if (ResultType
->isFunctionType()) {
5280 Diag(BaseExpr
->getBeginLoc(), diag::err_subscript_function_type
)
5281 << ResultType
<< BaseExpr
->getSourceRange();
5285 if (ResultType
->isVoidType() && !getLangOpts().CPlusPlus
) {
5286 // GNU extension: subscripting on pointer to void
5287 Diag(LLoc
, diag::ext_gnu_subscript_void_type
)
5288 << BaseExpr
->getSourceRange();
5290 // C forbids expressions of unqualified void type from being l-values.
5291 // See IsCForbiddenLValueType.
5292 if (!ResultType
.hasQualifiers())
5294 } else if (!ResultType
->isDependentType() &&
5295 !ResultType
.isWebAssemblyReferenceType() &&
5296 RequireCompleteSizedType(
5298 diag::err_subscript_incomplete_or_sizeless_type
, BaseExpr
))
5301 assert(VK
== VK_PRValue
|| LangOpts
.CPlusPlus
||
5302 !ResultType
.isCForbiddenLValueType());
5304 if (LHSExp
->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5305 FunctionScopes
.size() > 1) {
5307 LHSExp
->IgnoreParenImpCasts()->getType()->getAs
<TypedefType
>()) {
5308 for (auto I
= FunctionScopes
.rbegin(),
5309 E
= std::prev(FunctionScopes
.rend());
5311 auto *CSI
= dyn_cast
<CapturingScopeInfo
>(*I
);
5314 DeclContext
*DC
= nullptr;
5315 if (auto *LSI
= dyn_cast
<LambdaScopeInfo
>(CSI
))
5316 DC
= LSI
->CallOperator
;
5317 else if (auto *CRSI
= dyn_cast
<CapturedRegionScopeInfo
>(CSI
))
5318 DC
= CRSI
->TheCapturedDecl
;
5319 else if (auto *BSI
= dyn_cast
<BlockScopeInfo
>(CSI
))
5322 if (DC
->containsDecl(TT
->getDecl()))
5324 captureVariablyModifiedType(
5325 Context
, LHSExp
->IgnoreParenImpCasts()->getType(), CSI
);
5331 return new (Context
)
5332 ArraySubscriptExpr(LHSExp
, RHSExp
, ResultType
, VK
, OK
, RLoc
);
5335 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc
, FunctionDecl
*FD
,
5336 ParmVarDecl
*Param
, Expr
*RewrittenInit
,
5337 bool SkipImmediateInvocations
) {
5338 if (Param
->hasUnparsedDefaultArg()) {
5339 assert(!RewrittenInit
&& "Should not have a rewritten init expression yet");
5340 // If we've already cleared out the location for the default argument,
5341 // that means we're parsing it right now.
5342 if (!UnparsedDefaultArgLocs
.count(Param
)) {
5343 Diag(Param
->getBeginLoc(), diag::err_recursive_default_argument
) << FD
;
5344 Diag(CallLoc
, diag::note_recursive_default_argument_used_here
);
5345 Param
->setInvalidDecl();
5349 Diag(CallLoc
, diag::err_use_of_default_argument_to_function_declared_later
)
5350 << FD
<< cast
<CXXRecordDecl
>(FD
->getDeclContext());
5351 Diag(UnparsedDefaultArgLocs
[Param
],
5352 diag::note_default_argument_declared_here
);
5356 if (Param
->hasUninstantiatedDefaultArg()) {
5357 assert(!RewrittenInit
&& "Should not have a rewitten init expression yet");
5358 if (InstantiateDefaultArgument(CallLoc
, FD
, Param
))
5362 Expr
*Init
= RewrittenInit
? RewrittenInit
: Param
->getInit();
5363 assert(Init
&& "default argument but no initializer?");
5365 // If the default expression creates temporaries, we need to
5366 // push them to the current stack of expression temporaries so they'll
5367 // be properly destroyed.
5368 // FIXME: We should really be rebuilding the default argument with new
5369 // bound temporaries; see the comment in PR5810.
5370 // We don't need to do that with block decls, though, because
5371 // blocks in default argument expression can never capture anything.
5372 if (auto *InitWithCleanup
= dyn_cast
<ExprWithCleanups
>(Init
)) {
5373 // Set the "needs cleanups" bit regardless of whether there are
5374 // any explicit objects.
5375 Cleanup
.setExprNeedsCleanups(InitWithCleanup
->cleanupsHaveSideEffects());
5376 // Append all the objects to the cleanup list. Right now, this
5377 // should always be a no-op, because blocks in default argument
5378 // expressions should never be able to capture anything.
5379 assert(!InitWithCleanup
->getNumObjects() &&
5380 "default argument expression has capturing blocks?");
5382 // C++ [expr.const]p15.1:
5383 // An expression or conversion is in an immediate function context if it is
5384 // potentially evaluated and [...] its innermost enclosing non-block scope
5385 // is a function parameter scope of an immediate function.
5386 EnterExpressionEvaluationContext
EvalContext(
5388 FD
->isImmediateFunction()
5389 ? ExpressionEvaluationContext::ImmediateFunctionContext
5390 : ExpressionEvaluationContext::PotentiallyEvaluated
,
5392 ExprEvalContexts
.back().IsCurrentlyCheckingDefaultArgumentOrInitializer
=
5393 SkipImmediateInvocations
;
5394 runWithSufficientStackSpace(CallLoc
, [&] {
5395 MarkDeclarationsReferencedInExpr(Init
, /*SkipLocalVariables=*/true);
5400 struct ImmediateCallVisitor
: DynamicRecursiveASTVisitor
{
5401 const ASTContext
&Context
;
5402 ImmediateCallVisitor(const ASTContext
&Ctx
) : Context(Ctx
) {
5403 ShouldVisitImplicitCode
= true;
5406 bool HasImmediateCalls
= false;
5408 bool VisitCallExpr(CallExpr
*E
) override
{
5409 if (const FunctionDecl
*FD
= E
->getDirectCallee())
5410 HasImmediateCalls
|= FD
->isImmediateFunction();
5411 return DynamicRecursiveASTVisitor::VisitStmt(E
);
5414 bool VisitCXXConstructExpr(CXXConstructExpr
*E
) override
{
5415 if (const FunctionDecl
*FD
= E
->getConstructor())
5416 HasImmediateCalls
|= FD
->isImmediateFunction();
5417 return DynamicRecursiveASTVisitor::VisitStmt(E
);
5420 // SourceLocExpr are not immediate invocations
5421 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5422 // need to be rebuilt so that they refer to the correct SourceLocation and
5424 bool VisitSourceLocExpr(SourceLocExpr
*E
) override
{
5425 HasImmediateCalls
= true;
5426 return DynamicRecursiveASTVisitor::VisitStmt(E
);
5429 // A nested lambda might have parameters with immediate invocations
5430 // in their default arguments.
5431 // The compound statement is not visited (as it does not constitute a
5433 // FIXME: We should consider visiting and transforming captures
5434 // with init expressions.
5435 bool VisitLambdaExpr(LambdaExpr
*E
) override
{
5436 return VisitCXXMethodDecl(E
->getCallOperator());
5439 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr
*E
) override
{
5440 return TraverseStmt(E
->getExpr());
5443 bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr
*E
) override
{
5444 return TraverseStmt(E
->getExpr());
5448 struct EnsureImmediateInvocationInDefaultArgs
5449 : TreeTransform
<EnsureImmediateInvocationInDefaultArgs
> {
5450 EnsureImmediateInvocationInDefaultArgs(Sema
&SemaRef
)
5451 : TreeTransform(SemaRef
) {}
5453 bool AlwaysRebuild() { return true; }
5455 // Lambda can only have immediate invocations in the default
5456 // args of their parameters, which is transformed upon calling the closure.
5457 // The body is not a subexpression, so we have nothing to do.
5458 // FIXME: Immediate calls in capture initializers should be transformed.
5459 ExprResult
TransformLambdaExpr(LambdaExpr
*E
) { return E
; }
5460 ExprResult
TransformBlockExpr(BlockExpr
*E
) { return E
; }
5462 // Make sure we don't rebuild the this pointer as it would
5463 // cause it to incorrectly point it to the outermost class
5464 // in the case of nested struct initialization.
5465 ExprResult
TransformCXXThisExpr(CXXThisExpr
*E
) { return E
; }
5467 // Rewrite to source location to refer to the context in which they are used.
5468 ExprResult
TransformSourceLocExpr(SourceLocExpr
*E
) {
5469 DeclContext
*DC
= E
->getParentContext();
5470 if (DC
== SemaRef
.CurContext
)
5473 // FIXME: During instantiation, because the rebuild of defaults arguments
5474 // is not always done in the context of the template instantiator,
5475 // we run the risk of producing a dependent source location
5476 // that would never be rebuilt.
5477 // This usually happens during overload resolution, or in contexts
5478 // where the value of the source location does not matter.
5479 // However, we should find a better way to deal with source location
5480 // of function templates.
5481 if (!SemaRef
.CurrentInstantiationScope
||
5482 !SemaRef
.CurContext
->isDependentContext() || DC
->isDependentContext())
5483 DC
= SemaRef
.CurContext
;
5485 return getDerived().RebuildSourceLocExpr(
5486 E
->getIdentKind(), E
->getType(), E
->getBeginLoc(), E
->getEndLoc(), DC
);
5490 ExprResult
Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc
,
5491 FunctionDecl
*FD
, ParmVarDecl
*Param
,
5493 assert(Param
->hasDefaultArg() && "can't build nonexistent default arg");
5495 bool NestedDefaultChecking
= isCheckingDefaultArgumentOrInitializer();
5496 bool NeedRebuild
= needsRebuildOfDefaultArgOrInit();
5497 std::optional
<ExpressionEvaluationContextRecord::InitializationContext
>
5498 InitializationContext
=
5499 OutermostDeclarationWithDelayedImmediateInvocations();
5500 if (!InitializationContext
.has_value())
5501 InitializationContext
.emplace(CallLoc
, Param
, CurContext
);
5503 if (!Init
&& !Param
->hasUnparsedDefaultArg()) {
5504 // Mark that we are replacing a default argument first.
5505 // If we are instantiating a template we won't have to
5506 // retransform immediate calls.
5507 // C++ [expr.const]p15.1:
5508 // An expression or conversion is in an immediate function context if it
5509 // is potentially evaluated and [...] its innermost enclosing non-block
5510 // scope is a function parameter scope of an immediate function.
5511 EnterExpressionEvaluationContext
EvalContext(
5513 FD
->isImmediateFunction()
5514 ? ExpressionEvaluationContext::ImmediateFunctionContext
5515 : ExpressionEvaluationContext::PotentiallyEvaluated
,
5518 if (Param
->hasUninstantiatedDefaultArg()) {
5519 if (InstantiateDefaultArgument(CallLoc
, FD
, Param
))
5523 // An immediate invocation that is not evaluated where it appears is
5524 // evaluated and checked for whether it is a constant expression at the
5525 // point where the enclosing initializer is used in a function call.
5526 ImmediateCallVisitor
V(getASTContext());
5527 if (!NestedDefaultChecking
)
5528 V
.TraverseDecl(Param
);
5530 // Rewrite the call argument that was created from the corresponding
5531 // parameter's default argument.
5532 if (V
.HasImmediateCalls
||
5533 (NeedRebuild
&& isa_and_present
<ExprWithCleanups
>(Param
->getInit()))) {
5534 if (V
.HasImmediateCalls
)
5535 ExprEvalContexts
.back().DelayedDefaultInitializationContext
= {
5536 CallLoc
, Param
, CurContext
};
5537 // Pass down lifetime extending flag, and collect temporaries in
5538 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5539 currentEvaluationContext().InLifetimeExtendingContext
=
5540 parentEvaluationContext().InLifetimeExtendingContext
;
5541 EnsureImmediateInvocationInDefaultArgs
Immediate(*this);
5543 runWithSufficientStackSpace(CallLoc
, [&] {
5544 Res
= Immediate
.TransformInitializer(Param
->getInit(),
5547 if (Res
.isInvalid())
5549 Res
= ConvertParamDefaultArgument(Param
, Res
.get(),
5550 Res
.get()->getBeginLoc());
5551 if (Res
.isInvalid())
5557 if (CheckCXXDefaultArgExpr(
5558 CallLoc
, FD
, Param
, Init
,
5559 /*SkipImmediateInvocations=*/NestedDefaultChecking
))
5562 return CXXDefaultArgExpr::Create(Context
, InitializationContext
->Loc
, Param
,
5563 Init
, InitializationContext
->Context
);
5566 static FieldDecl
*FindFieldDeclInstantiationPattern(const ASTContext
&Ctx
,
5568 if (FieldDecl
*Pattern
= Ctx
.getInstantiatedFromUnnamedFieldDecl(Field
))
5570 auto *ParentRD
= cast
<CXXRecordDecl
>(Field
->getParent());
5571 CXXRecordDecl
*ClassPattern
= ParentRD
->getTemplateInstantiationPattern();
5572 DeclContext::lookup_result Lookup
=
5573 ClassPattern
->lookup(Field
->getDeclName());
5574 auto Rng
= llvm::make_filter_range(
5575 Lookup
, [](auto &&L
) { return isa
<FieldDecl
>(*L
); });
5578 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5579 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5580 // && "Duplicated instantiation pattern for field decl");
5581 return cast
<FieldDecl
>(*Rng
.begin());
5584 ExprResult
Sema::BuildCXXDefaultInitExpr(SourceLocation Loc
, FieldDecl
*Field
) {
5585 assert(Field
->hasInClassInitializer());
5587 // If we might have already tried and failed to instantiate, don't try again.
5588 if (Field
->isInvalidDecl())
5591 CXXThisScopeRAII
This(*this, Field
->getParent(), Qualifiers());
5593 auto *ParentRD
= cast
<CXXRecordDecl
>(Field
->getParent());
5595 std::optional
<ExpressionEvaluationContextRecord::InitializationContext
>
5596 InitializationContext
=
5597 OutermostDeclarationWithDelayedImmediateInvocations();
5598 if (!InitializationContext
.has_value())
5599 InitializationContext
.emplace(Loc
, Field
, CurContext
);
5601 Expr
*Init
= nullptr;
5603 bool NestedDefaultChecking
= isCheckingDefaultArgumentOrInitializer();
5604 bool NeedRebuild
= needsRebuildOfDefaultArgOrInit();
5605 EnterExpressionEvaluationContext
EvalContext(
5606 *this, ExpressionEvaluationContext::PotentiallyEvaluated
, Field
);
5608 if (!Field
->getInClassInitializer()) {
5609 // Maybe we haven't instantiated the in-class initializer. Go check the
5610 // pattern FieldDecl to see if it has one.
5611 if (isTemplateInstantiation(ParentRD
->getTemplateSpecializationKind())) {
5612 FieldDecl
*Pattern
=
5613 FindFieldDeclInstantiationPattern(getASTContext(), Field
);
5614 assert(Pattern
&& "We must have set the Pattern!");
5615 if (!Pattern
->hasInClassInitializer() ||
5616 InstantiateInClassInitializer(Loc
, Field
, Pattern
,
5617 getTemplateInstantiationArgs(Field
))) {
5618 Field
->setInvalidDecl();
5625 // An immediate invocation that is not evaluated where it appears is
5626 // evaluated and checked for whether it is a constant expression at the
5627 // point where the enclosing initializer is used in a [...] a constructor
5628 // definition, or an aggregate initialization.
5629 ImmediateCallVisitor
V(getASTContext());
5630 if (!NestedDefaultChecking
)
5631 V
.TraverseDecl(Field
);
5634 // Support lifetime extension of temporary created by aggregate
5635 // initialization using a default member initializer. We should rebuild
5636 // the initializer in a lifetime extension context if the initializer
5637 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5638 // extension code recurses into the default initializer and does lifetime
5639 // extension when warranted.
5640 bool ContainsAnyTemporaries
=
5641 isa_and_present
<ExprWithCleanups
>(Field
->getInClassInitializer());
5642 if (Field
->getInClassInitializer() &&
5643 !Field
->getInClassInitializer()->containsErrors() &&
5644 (V
.HasImmediateCalls
|| (NeedRebuild
&& ContainsAnyTemporaries
))) {
5645 ExprEvalContexts
.back().DelayedDefaultInitializationContext
= {Loc
, Field
,
5647 ExprEvalContexts
.back().IsCurrentlyCheckingDefaultArgumentOrInitializer
=
5648 NestedDefaultChecking
;
5649 // Pass down lifetime extending flag, and collect temporaries in
5650 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5651 currentEvaluationContext().InLifetimeExtendingContext
=
5652 parentEvaluationContext().InLifetimeExtendingContext
;
5653 EnsureImmediateInvocationInDefaultArgs
Immediate(*this);
5655 runWithSufficientStackSpace(Loc
, [&] {
5656 Res
= Immediate
.TransformInitializer(Field
->getInClassInitializer(),
5657 /*CXXDirectInit=*/false);
5659 if (!Res
.isInvalid())
5660 Res
= ConvertMemberDefaultInitExpression(Field
, Res
.get(), Loc
);
5661 if (Res
.isInvalid()) {
5662 Field
->setInvalidDecl();
5668 if (Field
->getInClassInitializer()) {
5669 Expr
*E
= Init
? Init
: Field
->getInClassInitializer();
5670 if (!NestedDefaultChecking
)
5671 runWithSufficientStackSpace(Loc
, [&] {
5672 MarkDeclarationsReferencedInExpr(E
, /*SkipLocalVariables=*/false);
5674 if (isInLifetimeExtendingContext())
5675 DiscardCleanupsInEvaluationContext();
5676 // C++11 [class.base.init]p7:
5677 // The initialization of each base and member constitutes a
5679 ExprResult Res
= ActOnFinishFullExpr(E
, /*DiscardedValue=*/false);
5680 if (Res
.isInvalid()) {
5681 Field
->setInvalidDecl();
5686 return CXXDefaultInitExpr::Create(Context
, InitializationContext
->Loc
,
5687 Field
, InitializationContext
->Context
,
5692 // If the brace-or-equal-initializer of a non-static data member
5693 // invokes a defaulted default constructor of its class or of an
5694 // enclosing class in a potentially evaluated subexpression, the
5695 // program is ill-formed.
5697 // This resolution is unworkable: the exception specification of the
5698 // default constructor can be needed in an unevaluated context, in
5699 // particular, in the operand of a noexcept-expression, and we can be
5700 // unable to compute an exception specification for an enclosed class.
5702 // Any attempt to resolve the exception specification of a defaulted default
5703 // constructor before the initializer is lexically complete will ultimately
5704 // come here at which point we can diagnose it.
5705 RecordDecl
*OutermostClass
= ParentRD
->getOuterLexicalRecordContext();
5706 Diag(Loc
, diag::err_default_member_initializer_not_yet_parsed
)
5707 << OutermostClass
<< Field
;
5708 Diag(Field
->getEndLoc(),
5709 diag::note_default_member_initializer_not_yet_parsed
);
5710 // Recover by marking the field invalid, unless we're in a SFINAE context.
5711 if (!isSFINAEContext())
5712 Field
->setInvalidDecl();
5716 Sema::VariadicCallType
5717 Sema::getVariadicCallType(FunctionDecl
*FDecl
, const FunctionProtoType
*Proto
,
5719 if (Proto
&& Proto
->isVariadic()) {
5720 if (isa_and_nonnull
<CXXConstructorDecl
>(FDecl
))
5721 return VariadicConstructor
;
5722 else if (Fn
&& Fn
->getType()->isBlockPointerType())
5723 return VariadicBlock
;
5725 if (CXXMethodDecl
*Method
= dyn_cast_or_null
<CXXMethodDecl
>(FDecl
))
5726 if (Method
->isInstance())
5727 return VariadicMethod
;
5728 } else if (Fn
&& Fn
->getType() == Context
.BoundMemberTy
)
5729 return VariadicMethod
;
5730 return VariadicFunction
;
5732 return VariadicDoesNotApply
;
5736 class FunctionCallCCC final
: public FunctionCallFilterCCC
{
5738 FunctionCallCCC(Sema
&SemaRef
, const IdentifierInfo
*FuncName
,
5739 unsigned NumArgs
, MemberExpr
*ME
)
5740 : FunctionCallFilterCCC(SemaRef
, NumArgs
, false, ME
),
5741 FunctionName(FuncName
) {}
5743 bool ValidateCandidate(const TypoCorrection
&candidate
) override
{
5744 if (!candidate
.getCorrectionSpecifier() ||
5745 candidate
.getCorrectionAsIdentifierInfo() != FunctionName
) {
5749 return FunctionCallFilterCCC::ValidateCandidate(candidate
);
5752 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
5753 return std::make_unique
<FunctionCallCCC
>(*this);
5757 const IdentifierInfo
*const FunctionName
;
5761 static TypoCorrection
TryTypoCorrectionForCall(Sema
&S
, Expr
*Fn
,
5762 FunctionDecl
*FDecl
,
5763 ArrayRef
<Expr
*> Args
) {
5764 MemberExpr
*ME
= dyn_cast
<MemberExpr
>(Fn
);
5765 DeclarationName FuncName
= FDecl
->getDeclName();
5766 SourceLocation NameLoc
= ME
? ME
->getMemberLoc() : Fn
->getBeginLoc();
5768 FunctionCallCCC
CCC(S
, FuncName
.getAsIdentifierInfo(), Args
.size(), ME
);
5769 if (TypoCorrection Corrected
= S
.CorrectTypo(
5770 DeclarationNameInfo(FuncName
, NameLoc
), Sema::LookupOrdinaryName
,
5771 S
.getScopeForContext(S
.CurContext
), nullptr, CCC
,
5772 Sema::CTK_ErrorRecovery
)) {
5773 if (NamedDecl
*ND
= Corrected
.getFoundDecl()) {
5774 if (Corrected
.isOverloaded()) {
5775 OverloadCandidateSet
OCS(NameLoc
, OverloadCandidateSet::CSK_Normal
);
5776 OverloadCandidateSet::iterator Best
;
5777 for (NamedDecl
*CD
: Corrected
) {
5778 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(CD
))
5779 S
.AddOverloadCandidate(FD
, DeclAccessPair::make(FD
, AS_none
), Args
,
5782 switch (OCS
.BestViableFunction(S
, NameLoc
, Best
)) {
5784 ND
= Best
->FoundDecl
;
5785 Corrected
.setCorrectionDecl(ND
);
5791 ND
= ND
->getUnderlyingDecl();
5792 if (isa
<ValueDecl
>(ND
) || isa
<FunctionTemplateDecl
>(ND
))
5796 return TypoCorrection();
5799 // [C++26][[expr.unary.op]/p4
5800 // A pointer to member is only formed when an explicit &
5801 // is used and its operand is a qualified-id not enclosed in parentheses.
5802 static bool isParenthetizedAndQualifiedAddressOfExpr(Expr
*Fn
) {
5803 if (!isa
<ParenExpr
>(Fn
))
5806 Fn
= Fn
->IgnoreParens();
5808 auto *UO
= dyn_cast
<UnaryOperator
>(Fn
);
5809 if (!UO
|| UO
->getOpcode() != clang::UO_AddrOf
)
5811 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(UO
->getSubExpr()->IgnoreParens())) {
5812 return DRE
->hasQualifier();
5814 if (auto *OVL
= dyn_cast
<OverloadExpr
>(UO
->getSubExpr()->IgnoreParens()))
5815 return OVL
->getQualifier();
5820 Sema::ConvertArgumentsForCall(CallExpr
*Call
, Expr
*Fn
,
5821 FunctionDecl
*FDecl
,
5822 const FunctionProtoType
*Proto
,
5823 ArrayRef
<Expr
*> Args
,
5824 SourceLocation RParenLoc
,
5825 bool IsExecConfig
) {
5826 // Bail out early if calling a builtin with custom typechecking.
5828 if (unsigned ID
= FDecl
->getBuiltinID())
5829 if (Context
.BuiltinInfo
.hasCustomTypechecking(ID
))
5832 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5833 // assignment, to the types of the corresponding parameter, ...
5835 bool AddressOf
= isParenthetizedAndQualifiedAddressOfExpr(Fn
);
5836 bool HasExplicitObjectParameter
=
5837 !AddressOf
&& FDecl
&& FDecl
->hasCXXExplicitFunctionObjectParameter();
5838 unsigned ExplicitObjectParameterOffset
= HasExplicitObjectParameter
? 1 : 0;
5839 unsigned NumParams
= Proto
->getNumParams();
5840 bool Invalid
= false;
5841 unsigned MinArgs
= FDecl
? FDecl
->getMinRequiredArguments() : NumParams
;
5842 unsigned FnKind
= Fn
->getType()->isBlockPointerType()
5844 : (IsExecConfig
? 3 /* kernel function (exec config) */
5845 : 0 /* function */);
5847 // If too few arguments are available (and we don't have default
5848 // arguments for the remaining parameters), don't make the call.
5849 if (Args
.size() < NumParams
) {
5850 if (Args
.size() < MinArgs
) {
5852 if (FDecl
&& (TC
= TryTypoCorrectionForCall(*this, Fn
, FDecl
, Args
))) {
5854 MinArgs
== NumParams
&& !Proto
->isVariadic()
5855 ? diag::err_typecheck_call_too_few_args_suggest
5856 : diag::err_typecheck_call_too_few_args_at_least_suggest
;
5859 << FnKind
<< MinArgs
- ExplicitObjectParameterOffset
5860 << static_cast<unsigned>(Args
.size()) -
5861 ExplicitObjectParameterOffset
5862 << HasExplicitObjectParameter
<< TC
.getCorrectionRange());
5863 } else if (MinArgs
- ExplicitObjectParameterOffset
== 1 && FDecl
&&
5864 FDecl
->getParamDecl(ExplicitObjectParameterOffset
)
5867 MinArgs
== NumParams
&& !Proto
->isVariadic()
5868 ? diag::err_typecheck_call_too_few_args_one
5869 : diag::err_typecheck_call_too_few_args_at_least_one
)
5870 << FnKind
<< FDecl
->getParamDecl(ExplicitObjectParameterOffset
)
5871 << HasExplicitObjectParameter
<< Fn
->getSourceRange();
5873 Diag(RParenLoc
, MinArgs
== NumParams
&& !Proto
->isVariadic()
5874 ? diag::err_typecheck_call_too_few_args
5875 : diag::err_typecheck_call_too_few_args_at_least
)
5876 << FnKind
<< MinArgs
- ExplicitObjectParameterOffset
5877 << static_cast<unsigned>(Args
.size()) -
5878 ExplicitObjectParameterOffset
5879 << HasExplicitObjectParameter
<< Fn
->getSourceRange();
5881 // Emit the location of the prototype.
5882 if (!TC
&& FDecl
&& !FDecl
->getBuiltinID() && !IsExecConfig
)
5883 Diag(FDecl
->getLocation(), diag::note_callee_decl
)
5884 << FDecl
<< FDecl
->getParametersSourceRange();
5888 // We reserve space for the default arguments when we create
5889 // the call expression, before calling ConvertArgumentsForCall.
5890 assert((Call
->getNumArgs() == NumParams
) &&
5891 "We should have reserved space for the default arguments before!");
5894 // If too many are passed and not variadic, error on the extras and drop
5896 if (Args
.size() > NumParams
) {
5897 if (!Proto
->isVariadic()) {
5899 if (FDecl
&& (TC
= TryTypoCorrectionForCall(*this, Fn
, FDecl
, Args
))) {
5901 MinArgs
== NumParams
&& !Proto
->isVariadic()
5902 ? diag::err_typecheck_call_too_many_args_suggest
5903 : diag::err_typecheck_call_too_many_args_at_most_suggest
;
5906 << FnKind
<< NumParams
- ExplicitObjectParameterOffset
5907 << static_cast<unsigned>(Args
.size()) -
5908 ExplicitObjectParameterOffset
5909 << HasExplicitObjectParameter
<< TC
.getCorrectionRange());
5910 } else if (NumParams
- ExplicitObjectParameterOffset
== 1 && FDecl
&&
5911 FDecl
->getParamDecl(ExplicitObjectParameterOffset
)
5913 Diag(Args
[NumParams
]->getBeginLoc(),
5914 MinArgs
== NumParams
5915 ? diag::err_typecheck_call_too_many_args_one
5916 : diag::err_typecheck_call_too_many_args_at_most_one
)
5917 << FnKind
<< FDecl
->getParamDecl(ExplicitObjectParameterOffset
)
5918 << static_cast<unsigned>(Args
.size()) -
5919 ExplicitObjectParameterOffset
5920 << HasExplicitObjectParameter
<< Fn
->getSourceRange()
5921 << SourceRange(Args
[NumParams
]->getBeginLoc(),
5922 Args
.back()->getEndLoc());
5924 Diag(Args
[NumParams
]->getBeginLoc(),
5925 MinArgs
== NumParams
5926 ? diag::err_typecheck_call_too_many_args
5927 : diag::err_typecheck_call_too_many_args_at_most
)
5928 << FnKind
<< NumParams
- ExplicitObjectParameterOffset
5929 << static_cast<unsigned>(Args
.size()) -
5930 ExplicitObjectParameterOffset
5931 << HasExplicitObjectParameter
<< Fn
->getSourceRange()
5932 << SourceRange(Args
[NumParams
]->getBeginLoc(),
5933 Args
.back()->getEndLoc());
5935 // Emit the location of the prototype.
5936 if (!TC
&& FDecl
&& !FDecl
->getBuiltinID() && !IsExecConfig
)
5937 Diag(FDecl
->getLocation(), diag::note_callee_decl
)
5938 << FDecl
<< FDecl
->getParametersSourceRange();
5940 // This deletes the extra arguments.
5941 Call
->shrinkNumArgs(NumParams
);
5945 SmallVector
<Expr
*, 8> AllArgs
;
5946 VariadicCallType CallType
= getVariadicCallType(FDecl
, Proto
, Fn
);
5948 Invalid
= GatherArgumentsForCall(Call
->getBeginLoc(), FDecl
, Proto
, 0, Args
,
5952 unsigned TotalNumArgs
= AllArgs
.size();
5953 for (unsigned i
= 0; i
< TotalNumArgs
; ++i
)
5954 Call
->setArg(i
, AllArgs
[i
]);
5956 Call
->computeDependence();
5960 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc
, FunctionDecl
*FDecl
,
5961 const FunctionProtoType
*Proto
,
5962 unsigned FirstParam
, ArrayRef
<Expr
*> Args
,
5963 SmallVectorImpl
<Expr
*> &AllArgs
,
5964 VariadicCallType CallType
, bool AllowExplicit
,
5965 bool IsListInitialization
) {
5966 unsigned NumParams
= Proto
->getNumParams();
5967 bool Invalid
= false;
5969 // Continue to check argument types (even if we have too few/many args).
5970 for (unsigned i
= FirstParam
; i
< NumParams
; i
++) {
5971 QualType ProtoArgType
= Proto
->getParamType(i
);
5974 ParmVarDecl
*Param
= FDecl
? FDecl
->getParamDecl(i
) : nullptr;
5975 if (ArgIx
< Args
.size()) {
5976 Arg
= Args
[ArgIx
++];
5978 if (RequireCompleteType(Arg
->getBeginLoc(), ProtoArgType
,
5979 diag::err_call_incomplete_argument
, Arg
))
5982 // Strip the unbridged-cast placeholder expression off, if applicable.
5983 bool CFAudited
= false;
5984 if (Arg
->getType() == Context
.ARCUnbridgedCastTy
&&
5985 FDecl
&& FDecl
->hasAttr
<CFAuditedTransferAttr
>() &&
5986 (!Param
|| !Param
->hasAttr
<CFConsumedAttr
>()))
5987 Arg
= ObjC().stripARCUnbridgedCast(Arg
);
5988 else if (getLangOpts().ObjCAutoRefCount
&&
5989 FDecl
&& FDecl
->hasAttr
<CFAuditedTransferAttr
>() &&
5990 (!Param
|| !Param
->hasAttr
<CFConsumedAttr
>()))
5993 if (Proto
->getExtParameterInfo(i
).isNoEscape() &&
5994 ProtoArgType
->isBlockPointerType())
5995 if (auto *BE
= dyn_cast
<BlockExpr
>(Arg
->IgnoreParenNoopCasts(Context
)))
5996 BE
->getBlockDecl()->setDoesNotEscape();
5997 if ((Proto
->getExtParameterInfo(i
).getABI() == ParameterABI::HLSLOut
||
5998 Proto
->getExtParameterInfo(i
).getABI() == ParameterABI::HLSLInOut
)) {
5999 ExprResult ArgExpr
= HLSL().ActOnOutParamExpr(Param
, Arg
);
6000 if (ArgExpr
.isInvalid())
6002 Arg
= ArgExpr
.getAs
<Expr
>();
6005 InitializedEntity Entity
=
6006 Param
? InitializedEntity::InitializeParameter(Context
, Param
,
6008 : InitializedEntity::InitializeParameter(
6009 Context
, ProtoArgType
, Proto
->isParamConsumed(i
));
6011 // Remember that parameter belongs to a CF audited API.
6013 Entity
.setParameterCFAudited();
6015 ExprResult ArgE
= PerformCopyInitialization(
6016 Entity
, SourceLocation(), Arg
, IsListInitialization
, AllowExplicit
);
6017 if (ArgE
.isInvalid())
6020 Arg
= ArgE
.getAs
<Expr
>();
6022 assert(Param
&& "can't use default arguments without a known callee");
6024 ExprResult ArgExpr
= BuildCXXDefaultArgExpr(CallLoc
, FDecl
, Param
);
6025 if (ArgExpr
.isInvalid())
6028 Arg
= ArgExpr
.getAs
<Expr
>();
6031 // Check for array bounds violations for each argument to the call. This
6032 // check only triggers warnings when the argument isn't a more complex Expr
6033 // with its own checking, such as a BinaryOperator.
6034 CheckArrayAccess(Arg
);
6036 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6037 CheckStaticArrayArgument(CallLoc
, Param
, Arg
);
6039 AllArgs
.push_back(Arg
);
6042 // If this is a variadic call, handle args passed through "...".
6043 if (CallType
!= VariadicDoesNotApply
) {
6044 // Assume that extern "C" functions with variadic arguments that
6045 // return __unknown_anytype aren't *really* variadic.
6046 if (Proto
->getReturnType() == Context
.UnknownAnyTy
&& FDecl
&&
6047 FDecl
->isExternC()) {
6048 for (Expr
*A
: Args
.slice(ArgIx
)) {
6049 QualType paramType
; // ignored
6050 ExprResult arg
= checkUnknownAnyArg(CallLoc
, A
, paramType
);
6051 Invalid
|= arg
.isInvalid();
6052 AllArgs
.push_back(arg
.get());
6055 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6057 for (Expr
*A
: Args
.slice(ArgIx
)) {
6058 ExprResult Arg
= DefaultVariadicArgumentPromotion(A
, CallType
, FDecl
);
6059 Invalid
|= Arg
.isInvalid();
6060 AllArgs
.push_back(Arg
.get());
6064 // Check for array bounds violations.
6065 for (Expr
*A
: Args
.slice(ArgIx
))
6066 CheckArrayAccess(A
);
6071 static void DiagnoseCalleeStaticArrayParam(Sema
&S
, ParmVarDecl
*PVD
) {
6072 TypeLoc TL
= PVD
->getTypeSourceInfo()->getTypeLoc();
6073 if (DecayedTypeLoc DTL
= TL
.getAs
<DecayedTypeLoc
>())
6074 TL
= DTL
.getOriginalLoc();
6075 if (ArrayTypeLoc ATL
= TL
.getAs
<ArrayTypeLoc
>())
6076 S
.Diag(PVD
->getLocation(), diag::note_callee_static_array
)
6077 << ATL
.getLocalSourceRange();
6081 Sema::CheckStaticArrayArgument(SourceLocation CallLoc
,
6083 const Expr
*ArgExpr
) {
6084 // Static array parameters are not supported in C++.
6085 if (!Param
|| getLangOpts().CPlusPlus
)
6088 QualType OrigTy
= Param
->getOriginalType();
6090 const ArrayType
*AT
= Context
.getAsArrayType(OrigTy
);
6091 if (!AT
|| AT
->getSizeModifier() != ArraySizeModifier::Static
)
6094 if (ArgExpr
->isNullPointerConstant(Context
,
6095 Expr::NPC_NeverValueDependent
)) {
6096 Diag(CallLoc
, diag::warn_null_arg
) << ArgExpr
->getSourceRange();
6097 DiagnoseCalleeStaticArrayParam(*this, Param
);
6101 const ConstantArrayType
*CAT
= dyn_cast
<ConstantArrayType
>(AT
);
6105 const ConstantArrayType
*ArgCAT
=
6106 Context
.getAsConstantArrayType(ArgExpr
->IgnoreParenCasts()->getType());
6110 if (getASTContext().hasSameUnqualifiedType(CAT
->getElementType(),
6111 ArgCAT
->getElementType())) {
6112 if (ArgCAT
->getSize().ult(CAT
->getSize())) {
6113 Diag(CallLoc
, diag::warn_static_array_too_small
)
6114 << ArgExpr
->getSourceRange() << (unsigned)ArgCAT
->getZExtSize()
6115 << (unsigned)CAT
->getZExtSize() << 0;
6116 DiagnoseCalleeStaticArrayParam(*this, Param
);
6121 std::optional
<CharUnits
> ArgSize
=
6122 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT
);
6123 std::optional
<CharUnits
> ParmSize
=
6124 getASTContext().getTypeSizeInCharsIfKnown(CAT
);
6125 if (ArgSize
&& ParmSize
&& *ArgSize
< *ParmSize
) {
6126 Diag(CallLoc
, diag::warn_static_array_too_small
)
6127 << ArgExpr
->getSourceRange() << (unsigned)ArgSize
->getQuantity()
6128 << (unsigned)ParmSize
->getQuantity() << 1;
6129 DiagnoseCalleeStaticArrayParam(*this, Param
);
6133 /// Given a function expression of unknown-any type, try to rebuild it
6134 /// to have a function type.
6135 static ExprResult
rebuildUnknownAnyFunction(Sema
&S
, Expr
*fn
);
6137 /// Is the given type a placeholder that we need to lower out
6138 /// immediately during argument processing?
6139 static bool isPlaceholderToRemoveAsArg(QualType type
) {
6140 // Placeholders are never sugared.
6141 const BuiltinType
*placeholder
= dyn_cast
<BuiltinType
>(type
);
6142 if (!placeholder
) return false;
6144 switch (placeholder
->getKind()) {
6145 // Ignore all the non-placeholder types.
6146 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6147 case BuiltinType::Id:
6148 #include "clang/Basic/OpenCLImageTypes.def"
6149 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6150 case BuiltinType::Id:
6151 #include "clang/Basic/OpenCLExtensionTypes.def"
6152 // In practice we'll never use this, since all SVE types are sugared
6153 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6154 #define SVE_TYPE(Name, Id, SingletonId) \
6155 case BuiltinType::Id:
6156 #include "clang/Basic/AArch64SVEACLETypes.def"
6157 #define PPC_VECTOR_TYPE(Name, Id, Size) \
6158 case BuiltinType::Id:
6159 #include "clang/Basic/PPCTypes.def"
6160 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6161 #include "clang/Basic/RISCVVTypes.def"
6162 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6163 #include "clang/Basic/WebAssemblyReferenceTypes.def"
6164 #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6165 #include "clang/Basic/AMDGPUTypes.def"
6166 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6167 #include "clang/Basic/HLSLIntangibleTypes.def"
6168 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6169 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6170 #include "clang/AST/BuiltinTypes.def"
6173 case BuiltinType::UnresolvedTemplate
:
6174 // We cannot lower out overload sets; they might validly be resolved
6175 // by the call machinery.
6176 case BuiltinType::Overload
:
6179 // Unbridged casts in ARC can be handled in some call positions and
6180 // should be left in place.
6181 case BuiltinType::ARCUnbridgedCast
:
6184 // Pseudo-objects should be converted as soon as possible.
6185 case BuiltinType::PseudoObject
:
6188 // The debugger mode could theoretically but currently does not try
6189 // to resolve unknown-typed arguments based on known parameter types.
6190 case BuiltinType::UnknownAny
:
6193 // These are always invalid as call arguments and should be reported.
6194 case BuiltinType::BoundMember
:
6195 case BuiltinType::BuiltinFn
:
6196 case BuiltinType::IncompleteMatrixIdx
:
6197 case BuiltinType::ArraySection
:
6198 case BuiltinType::OMPArrayShaping
:
6199 case BuiltinType::OMPIterator
:
6203 llvm_unreachable("bad builtin type kind");
6206 bool Sema::CheckArgsForPlaceholders(MultiExprArg args
) {
6207 // Apply this processing to all the arguments at once instead of
6208 // dying at the first failure.
6209 bool hasInvalid
= false;
6210 for (size_t i
= 0, e
= args
.size(); i
!= e
; i
++) {
6211 if (isPlaceholderToRemoveAsArg(args
[i
]->getType())) {
6212 ExprResult result
= CheckPlaceholderExpr(args
[i
]);
6213 if (result
.isInvalid()) hasInvalid
= true;
6214 else args
[i
] = result
.get();
6220 /// If a builtin function has a pointer argument with no explicit address
6221 /// space, then it should be able to accept a pointer to any address
6222 /// space as input. In order to do this, we need to replace the
6223 /// standard builtin declaration with one that uses the same address space
6226 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6227 /// it does not contain any pointer arguments without
6228 /// an address space qualifer. Otherwise the rewritten
6229 /// FunctionDecl is returned.
6230 /// TODO: Handle pointer return types.
6231 static FunctionDecl
*rewriteBuiltinFunctionDecl(Sema
*Sema
, ASTContext
&Context
,
6232 FunctionDecl
*FDecl
,
6233 MultiExprArg ArgExprs
) {
6235 QualType DeclType
= FDecl
->getType();
6236 const FunctionProtoType
*FT
= dyn_cast
<FunctionProtoType
>(DeclType
);
6238 if (!Context
.BuiltinInfo
.hasPtrArgsOrResult(FDecl
->getBuiltinID()) || !FT
||
6239 ArgExprs
.size() < FT
->getNumParams())
6242 bool NeedsNewDecl
= false;
6244 SmallVector
<QualType
, 8> OverloadParams
;
6246 for (QualType ParamType
: FT
->param_types()) {
6248 // Convert array arguments to pointer to simplify type lookup.
6250 Sema
->DefaultFunctionArrayLvalueConversion(ArgExprs
[i
++]);
6251 if (ArgRes
.isInvalid())
6253 Expr
*Arg
= ArgRes
.get();
6254 QualType ArgType
= Arg
->getType();
6255 if (!ParamType
->isPointerType() || ParamType
.hasAddressSpace() ||
6256 !ArgType
->isPointerType() ||
6257 !ArgType
->getPointeeType().hasAddressSpace() ||
6258 isPtrSizeAddressSpace(ArgType
->getPointeeType().getAddressSpace())) {
6259 OverloadParams
.push_back(ParamType
);
6263 QualType PointeeType
= ParamType
->getPointeeType();
6264 if (PointeeType
.hasAddressSpace())
6267 NeedsNewDecl
= true;
6268 LangAS AS
= ArgType
->getPointeeType().getAddressSpace();
6270 PointeeType
= Context
.getAddrSpaceQualType(PointeeType
, AS
);
6271 OverloadParams
.push_back(Context
.getPointerType(PointeeType
));
6277 FunctionProtoType::ExtProtoInfo EPI
;
6278 EPI
.Variadic
= FT
->isVariadic();
6279 QualType OverloadTy
= Context
.getFunctionType(FT
->getReturnType(),
6280 OverloadParams
, EPI
);
6281 DeclContext
*Parent
= FDecl
->getParent();
6282 FunctionDecl
*OverloadDecl
= FunctionDecl::Create(
6283 Context
, Parent
, FDecl
->getLocation(), FDecl
->getLocation(),
6284 FDecl
->getIdentifier(), OverloadTy
,
6285 /*TInfo=*/nullptr, SC_Extern
, Sema
->getCurFPFeatures().isFPConstrained(),
6287 /*hasPrototype=*/true);
6288 SmallVector
<ParmVarDecl
*, 16> Params
;
6289 FT
= cast
<FunctionProtoType
>(OverloadTy
);
6290 for (unsigned i
= 0, e
= FT
->getNumParams(); i
!= e
; ++i
) {
6291 QualType ParamType
= FT
->getParamType(i
);
6293 ParmVarDecl::Create(Context
, OverloadDecl
, SourceLocation(),
6294 SourceLocation(), nullptr, ParamType
,
6295 /*TInfo=*/nullptr, SC_None
, nullptr);
6296 Parm
->setScopeInfo(0, i
);
6297 Params
.push_back(Parm
);
6299 OverloadDecl
->setParams(Params
);
6300 Sema
->mergeDeclAttributes(OverloadDecl
, FDecl
);
6301 return OverloadDecl
;
6304 static void checkDirectCallValidity(Sema
&S
, const Expr
*Fn
,
6305 FunctionDecl
*Callee
,
6306 MultiExprArg ArgExprs
) {
6307 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6308 // similar attributes) really don't like it when functions are called with an
6309 // invalid number of args.
6310 if (S
.TooManyArguments(Callee
->getNumParams(), ArgExprs
.size(),
6311 /*PartialOverloading=*/false) &&
6312 !Callee
->isVariadic())
6314 if (Callee
->getMinRequiredArguments() > ArgExprs
.size())
6317 if (const EnableIfAttr
*Attr
=
6318 S
.CheckEnableIf(Callee
, Fn
->getBeginLoc(), ArgExprs
, true)) {
6319 S
.Diag(Fn
->getBeginLoc(),
6320 isa
<CXXMethodDecl
>(Callee
)
6321 ? diag::err_ovl_no_viable_member_function_in_call
6322 : diag::err_ovl_no_viable_function_in_call
)
6323 << Callee
<< Callee
->getSourceRange();
6324 S
.Diag(Callee
->getLocation(),
6325 diag::note_ovl_candidate_disabled_by_function_cond_attr
)
6326 << Attr
->getCond()->getSourceRange() << Attr
->getMessage();
6331 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6332 const UnresolvedMemberExpr
*const UME
, Sema
&S
) {
6334 const auto GetFunctionLevelDCIfCXXClass
=
6335 [](Sema
&S
) -> const CXXRecordDecl
* {
6336 const DeclContext
*const DC
= S
.getFunctionLevelDeclContext();
6337 if (!DC
|| !DC
->getParent())
6340 // If the call to some member function was made from within a member
6341 // function body 'M' return return 'M's parent.
6342 if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(DC
))
6343 return MD
->getParent()->getCanonicalDecl();
6344 // else the call was made from within a default member initializer of a
6345 // class, so return the class.
6346 if (const auto *RD
= dyn_cast
<CXXRecordDecl
>(DC
))
6347 return RD
->getCanonicalDecl();
6350 // If our DeclContext is neither a member function nor a class (in the
6351 // case of a lambda in a default member initializer), we can't have an
6352 // enclosing 'this'.
6354 const CXXRecordDecl
*const CurParentClass
= GetFunctionLevelDCIfCXXClass(S
);
6355 if (!CurParentClass
)
6358 // The naming class for implicit member functions call is the class in which
6359 // name lookup starts.
6360 const CXXRecordDecl
*const NamingClass
=
6361 UME
->getNamingClass()->getCanonicalDecl();
6362 assert(NamingClass
&& "Must have naming class even for implicit access");
6364 // If the unresolved member functions were found in a 'naming class' that is
6365 // related (either the same or derived from) to the class that contains the
6366 // member function that itself contained the implicit member access.
6368 return CurParentClass
== NamingClass
||
6369 CurParentClass
->isDerivedFrom(NamingClass
);
6373 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6374 Sema
&S
, const UnresolvedMemberExpr
*const UME
, SourceLocation CallLoc
) {
6379 LambdaScopeInfo
*const CurLSI
= S
.getCurLambda();
6380 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6381 // already been captured, or if this is an implicit member function call (if
6382 // it isn't, an attempt to capture 'this' should already have been made).
6383 if (!CurLSI
|| CurLSI
->ImpCaptureStyle
== CurLSI
->ImpCap_None
||
6384 !UME
->isImplicitAccess() || CurLSI
->isCXXThisCaptured())
6387 // Check if the naming class in which the unresolved members were found is
6388 // related (same as or is a base of) to the enclosing class.
6390 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME
, S
))
6394 DeclContext
*EnclosingFunctionCtx
= S
.CurContext
->getParent()->getParent();
6395 // If the enclosing function is not dependent, then this lambda is
6396 // capture ready, so if we can capture this, do so.
6397 if (!EnclosingFunctionCtx
->isDependentContext()) {
6398 // If the current lambda and all enclosing lambdas can capture 'this' -
6399 // then go ahead and capture 'this' (since our unresolved overload set
6400 // contains at least one non-static member function).
6401 if (!S
.CheckCXXThisCapture(CallLoc
, /*Explcit*/ false, /*Diagnose*/ false))
6402 S
.CheckCXXThisCapture(CallLoc
);
6403 } else if (S
.CurContext
->isDependentContext()) {
6404 // ... since this is an implicit member reference, that might potentially
6405 // involve a 'this' capture, mark 'this' for potential capture in
6406 // enclosing lambdas.
6407 if (CurLSI
->ImpCaptureStyle
!= CurLSI
->ImpCap_None
)
6408 CurLSI
->addPotentialThisCapture(CallLoc
);
6412 // Once a call is fully resolved, warn for unqualified calls to specific
6413 // C++ standard functions, like move and forward.
6414 static void DiagnosedUnqualifiedCallsToStdFunctions(Sema
&S
,
6415 const CallExpr
*Call
) {
6416 // We are only checking unary move and forward so exit early here.
6417 if (Call
->getNumArgs() != 1)
6420 const Expr
*E
= Call
->getCallee()->IgnoreParenImpCasts();
6421 if (!E
|| isa
<UnresolvedLookupExpr
>(E
))
6423 const DeclRefExpr
*DRE
= dyn_cast_if_present
<DeclRefExpr
>(E
);
6424 if (!DRE
|| !DRE
->getLocation().isValid())
6427 if (DRE
->getQualifier())
6430 const FunctionDecl
*FD
= Call
->getDirectCallee();
6434 // Only warn for some functions deemed more frequent or problematic.
6435 unsigned BuiltinID
= FD
->getBuiltinID();
6436 if (BuiltinID
!= Builtin::BImove
&& BuiltinID
!= Builtin::BIforward
)
6439 S
.Diag(DRE
->getLocation(), diag::warn_unqualified_call_to_std_cast_function
)
6440 << FD
->getQualifiedNameAsString()
6441 << FixItHint::CreateInsertion(DRE
->getLocation(), "std::");
6444 ExprResult
Sema::ActOnCallExpr(Scope
*Scope
, Expr
*Fn
, SourceLocation LParenLoc
,
6445 MultiExprArg ArgExprs
, SourceLocation RParenLoc
,
6448 BuildCallExpr(Scope
, Fn
, LParenLoc
, ArgExprs
, RParenLoc
, ExecConfig
,
6449 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6450 if (Call
.isInvalid())
6453 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6455 if (const auto *ULE
= dyn_cast
<UnresolvedLookupExpr
>(Fn
);
6456 ULE
&& ULE
->hasExplicitTemplateArgs() &&
6457 ULE
->decls_begin() == ULE
->decls_end()) {
6458 Diag(Fn
->getExprLoc(), getLangOpts().CPlusPlus20
6459 ? diag::warn_cxx17_compat_adl_only_template_id
6460 : diag::ext_adl_only_template_id
)
6464 if (LangOpts
.OpenMP
)
6465 Call
= OpenMP().ActOnOpenMPCall(Call
, Scope
, LParenLoc
, ArgExprs
, RParenLoc
,
6467 if (LangOpts
.CPlusPlus
) {
6468 if (const auto *CE
= dyn_cast
<CallExpr
>(Call
.get()))
6469 DiagnosedUnqualifiedCallsToStdFunctions(*this, CE
);
6471 // If we previously found that the id-expression of this call refers to a
6472 // consteval function but the call is dependent, we should not treat is an
6473 // an invalid immediate call.
6474 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(Fn
->IgnoreParens());
6475 DRE
&& Call
.get()->isValueDependent()) {
6476 currentEvaluationContext().ReferenceToConsteval
.erase(DRE
);
6482 ExprResult
Sema::BuildCallExpr(Scope
*Scope
, Expr
*Fn
, SourceLocation LParenLoc
,
6483 MultiExprArg ArgExprs
, SourceLocation RParenLoc
,
6484 Expr
*ExecConfig
, bool IsExecConfig
,
6485 bool AllowRecovery
) {
6486 // Since this might be a postfix expression, get rid of ParenListExprs.
6487 ExprResult Result
= MaybeConvertParenListExprToParenExpr(Scope
, Fn
);
6488 if (Result
.isInvalid()) return ExprError();
6491 if (CheckArgsForPlaceholders(ArgExprs
))
6494 // The result of __builtin_counted_by_ref cannot be used as a function
6495 // argument. It allows leaking and modification of bounds safety information.
6496 for (const Expr
*Arg
: ArgExprs
)
6497 if (CheckInvalidBuiltinCountedByRef(Arg
, FunctionArgKind
))
6500 if (getLangOpts().CPlusPlus
) {
6501 // If this is a pseudo-destructor expression, build the call immediately.
6502 if (isa
<CXXPseudoDestructorExpr
>(Fn
)) {
6503 if (!ArgExprs
.empty()) {
6504 // Pseudo-destructor calls should not have any arguments.
6505 Diag(Fn
->getBeginLoc(), diag::err_pseudo_dtor_call_with_args
)
6506 << FixItHint::CreateRemoval(
6507 SourceRange(ArgExprs
.front()->getBeginLoc(),
6508 ArgExprs
.back()->getEndLoc()));
6511 return CallExpr::Create(Context
, Fn
, /*Args=*/{}, Context
.VoidTy
,
6512 VK_PRValue
, RParenLoc
, CurFPFeatureOverrides());
6514 if (Fn
->getType() == Context
.PseudoObjectTy
) {
6515 ExprResult result
= CheckPlaceholderExpr(Fn
);
6516 if (result
.isInvalid()) return ExprError();
6520 // Determine whether this is a dependent call inside a C++ template,
6521 // in which case we won't do any semantic analysis now.
6522 if (Fn
->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs
)) {
6524 return CUDAKernelCallExpr::Create(Context
, Fn
,
6525 cast
<CallExpr
>(ExecConfig
), ArgExprs
,
6526 Context
.DependentTy
, VK_PRValue
,
6527 RParenLoc
, CurFPFeatureOverrides());
6530 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6531 *this, dyn_cast
<UnresolvedMemberExpr
>(Fn
->IgnoreParens()),
6534 return CallExpr::Create(Context
, Fn
, ArgExprs
, Context
.DependentTy
,
6535 VK_PRValue
, RParenLoc
, CurFPFeatureOverrides());
6539 // Determine whether this is a call to an object (C++ [over.call.object]).
6540 if (Fn
->getType()->isRecordType())
6541 return BuildCallToObjectOfClassType(Scope
, Fn
, LParenLoc
, ArgExprs
,
6544 if (Fn
->getType() == Context
.UnknownAnyTy
) {
6545 ExprResult result
= rebuildUnknownAnyFunction(*this, Fn
);
6546 if (result
.isInvalid()) return ExprError();
6550 if (Fn
->getType() == Context
.BoundMemberTy
) {
6551 return BuildCallToMemberFunction(Scope
, Fn
, LParenLoc
, ArgExprs
,
6552 RParenLoc
, ExecConfig
, IsExecConfig
,
6557 // Check for overloaded calls. This can happen even in C due to extensions.
6558 if (Fn
->getType() == Context
.OverloadTy
) {
6559 OverloadExpr::FindResult find
= OverloadExpr::find(Fn
);
6561 // We aren't supposed to apply this logic if there's an '&' involved.
6562 if (!find
.HasFormOfMemberPointer
|| find
.IsAddressOfOperandWithParen
) {
6563 if (Expr::hasAnyTypeDependentArguments(ArgExprs
))
6564 return CallExpr::Create(Context
, Fn
, ArgExprs
, Context
.DependentTy
,
6565 VK_PRValue
, RParenLoc
, CurFPFeatureOverrides());
6566 OverloadExpr
*ovl
= find
.Expression
;
6567 if (UnresolvedLookupExpr
*ULE
= dyn_cast
<UnresolvedLookupExpr
>(ovl
))
6568 return BuildOverloadedCallExpr(
6569 Scope
, Fn
, ULE
, LParenLoc
, ArgExprs
, RParenLoc
, ExecConfig
,
6570 /*AllowTypoCorrection=*/true, find
.IsAddressOfOperand
);
6571 return BuildCallToMemberFunction(Scope
, Fn
, LParenLoc
, ArgExprs
,
6572 RParenLoc
, ExecConfig
, IsExecConfig
,
6577 // If we're directly calling a function, get the appropriate declaration.
6578 if (Fn
->getType() == Context
.UnknownAnyTy
) {
6579 ExprResult result
= rebuildUnknownAnyFunction(*this, Fn
);
6580 if (result
.isInvalid()) return ExprError();
6584 Expr
*NakedFn
= Fn
->IgnoreParens();
6586 bool CallingNDeclIndirectly
= false;
6587 NamedDecl
*NDecl
= nullptr;
6588 if (UnaryOperator
*UnOp
= dyn_cast
<UnaryOperator
>(NakedFn
)) {
6589 if (UnOp
->getOpcode() == UO_AddrOf
) {
6590 CallingNDeclIndirectly
= true;
6591 NakedFn
= UnOp
->getSubExpr()->IgnoreParens();
6595 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(NakedFn
)) {
6596 NDecl
= DRE
->getDecl();
6598 FunctionDecl
*FDecl
= dyn_cast
<FunctionDecl
>(NDecl
);
6599 if (FDecl
&& FDecl
->getBuiltinID()) {
6600 // Rewrite the function decl for this builtin by replacing parameters
6601 // with no explicit address space with the address space of the arguments
6604 rewriteBuiltinFunctionDecl(this, Context
, FDecl
, ArgExprs
))) {
6606 Fn
= DeclRefExpr::Create(
6607 Context
, FDecl
->getQualifierLoc(), SourceLocation(), FDecl
, false,
6608 SourceLocation(), FDecl
->getType(), Fn
->getValueKind(), FDecl
,
6609 nullptr, DRE
->isNonOdrUse());
6612 } else if (auto *ME
= dyn_cast
<MemberExpr
>(NakedFn
))
6613 NDecl
= ME
->getMemberDecl();
6615 if (FunctionDecl
*FD
= dyn_cast_or_null
<FunctionDecl
>(NDecl
)) {
6616 if (CallingNDeclIndirectly
&& !checkAddressOfFunctionIsAvailable(
6617 FD
, /*Complain=*/true, Fn
->getBeginLoc()))
6620 checkDirectCallValidity(*this, Fn
, FD
, ArgExprs
);
6622 // If this expression is a call to a builtin function in HIP device
6623 // compilation, allow a pointer-type argument to default address space to be
6624 // passed as a pointer-type parameter to a non-default address space.
6625 // If Arg is declared in the default address space and Param is declared
6626 // in a non-default address space, perform an implicit address space cast to
6627 // the parameter type.
6628 if (getLangOpts().HIP
&& getLangOpts().CUDAIsDevice
&& FD
&&
6629 FD
->getBuiltinID()) {
6630 for (unsigned Idx
= 0; Idx
< ArgExprs
.size() && Idx
< FD
->param_size();
6632 ParmVarDecl
*Param
= FD
->getParamDecl(Idx
);
6633 if (!ArgExprs
[Idx
] || !Param
|| !Param
->getType()->isPointerType() ||
6634 !ArgExprs
[Idx
]->getType()->isPointerType())
6637 auto ParamAS
= Param
->getType()->getPointeeType().getAddressSpace();
6638 auto ArgTy
= ArgExprs
[Idx
]->getType();
6639 auto ArgPtTy
= ArgTy
->getPointeeType();
6640 auto ArgAS
= ArgPtTy
.getAddressSpace();
6642 // Add address space cast if target address spaces are different
6643 bool NeedImplicitASC
=
6644 ParamAS
!= LangAS::Default
&& // Pointer params in generic AS don't need special handling.
6645 ( ArgAS
== LangAS::Default
|| // We do allow implicit conversion from generic AS
6646 // or from specific AS which has target AS matching that of Param.
6647 getASTContext().getTargetAddressSpace(ArgAS
) == getASTContext().getTargetAddressSpace(ParamAS
));
6648 if (!NeedImplicitASC
)
6651 // First, ensure that the Arg is an RValue.
6652 if (ArgExprs
[Idx
]->isGLValue()) {
6653 ArgExprs
[Idx
] = ImplicitCastExpr::Create(
6654 Context
, ArgExprs
[Idx
]->getType(), CK_NoOp
, ArgExprs
[Idx
],
6655 nullptr, VK_PRValue
, FPOptionsOverride());
6658 // Construct a new arg type with address space of Param
6659 Qualifiers ArgPtQuals
= ArgPtTy
.getQualifiers();
6660 ArgPtQuals
.setAddressSpace(ParamAS
);
6662 Context
.getQualifiedType(ArgPtTy
.getUnqualifiedType(), ArgPtQuals
);
6664 Context
.getQualifiedType(Context
.getPointerType(NewArgPtTy
),
6665 ArgTy
.getQualifiers());
6667 // Finally perform an implicit address space cast
6668 ArgExprs
[Idx
] = ImpCastExprToType(ArgExprs
[Idx
], NewArgTy
,
6669 CK_AddressSpaceConversion
)
6675 if (Context
.isDependenceAllowed() &&
6676 (Fn
->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs
))) {
6677 assert(!getLangOpts().CPlusPlus
);
6678 assert((Fn
->containsErrors() ||
6679 llvm::any_of(ArgExprs
,
6680 [](clang::Expr
*E
) { return E
->containsErrors(); })) &&
6681 "should only occur in error-recovery path.");
6682 return CallExpr::Create(Context
, Fn
, ArgExprs
, Context
.DependentTy
,
6683 VK_PRValue
, RParenLoc
, CurFPFeatureOverrides());
6685 return BuildResolvedCallExpr(Fn
, NDecl
, LParenLoc
, ArgExprs
, RParenLoc
,
6686 ExecConfig
, IsExecConfig
);
6689 Expr
*Sema::BuildBuiltinCallExpr(SourceLocation Loc
, Builtin::ID Id
,
6690 MultiExprArg CallArgs
) {
6691 StringRef Name
= Context
.BuiltinInfo
.getName(Id
);
6692 LookupResult
R(*this, &Context
.Idents
.get(Name
), Loc
,
6693 Sema::LookupOrdinaryName
);
6694 LookupName(R
, TUScope
, /*AllowBuiltinCreation=*/true);
6696 auto *BuiltInDecl
= R
.getAsSingle
<FunctionDecl
>();
6697 assert(BuiltInDecl
&& "failed to find builtin declaration");
6699 ExprResult DeclRef
=
6700 BuildDeclRefExpr(BuiltInDecl
, BuiltInDecl
->getType(), VK_LValue
, Loc
);
6701 assert(DeclRef
.isUsable() && "Builtin reference cannot fail");
6704 BuildCallExpr(/*Scope=*/nullptr, DeclRef
.get(), Loc
, CallArgs
, Loc
);
6706 assert(!Call
.isInvalid() && "Call to builtin cannot fail!");
6710 ExprResult
Sema::ActOnAsTypeExpr(Expr
*E
, ParsedType ParsedDestTy
,
6711 SourceLocation BuiltinLoc
,
6712 SourceLocation RParenLoc
) {
6713 QualType DstTy
= GetTypeFromParser(ParsedDestTy
);
6714 return BuildAsTypeExpr(E
, DstTy
, BuiltinLoc
, RParenLoc
);
6717 ExprResult
Sema::BuildAsTypeExpr(Expr
*E
, QualType DestTy
,
6718 SourceLocation BuiltinLoc
,
6719 SourceLocation RParenLoc
) {
6720 ExprValueKind VK
= VK_PRValue
;
6721 ExprObjectKind OK
= OK_Ordinary
;
6722 QualType SrcTy
= E
->getType();
6723 if (!SrcTy
->isDependentType() &&
6724 Context
.getTypeSize(DestTy
) != Context
.getTypeSize(SrcTy
))
6726 Diag(BuiltinLoc
, diag::err_invalid_astype_of_different_size
)
6727 << DestTy
<< SrcTy
<< E
->getSourceRange());
6728 return new (Context
) AsTypeExpr(E
, DestTy
, VK
, OK
, BuiltinLoc
, RParenLoc
);
6731 ExprResult
Sema::ActOnConvertVectorExpr(Expr
*E
, ParsedType ParsedDestTy
,
6732 SourceLocation BuiltinLoc
,
6733 SourceLocation RParenLoc
) {
6734 TypeSourceInfo
*TInfo
;
6735 GetTypeFromParser(ParsedDestTy
, &TInfo
);
6736 return ConvertVectorExpr(E
, TInfo
, BuiltinLoc
, RParenLoc
);
6739 ExprResult
Sema::BuildResolvedCallExpr(Expr
*Fn
, NamedDecl
*NDecl
,
6740 SourceLocation LParenLoc
,
6741 ArrayRef
<Expr
*> Args
,
6742 SourceLocation RParenLoc
, Expr
*Config
,
6743 bool IsExecConfig
, ADLCallKind UsesADL
) {
6744 FunctionDecl
*FDecl
= dyn_cast_or_null
<FunctionDecl
>(NDecl
);
6745 unsigned BuiltinID
= (FDecl
? FDecl
->getBuiltinID() : 0);
6747 // Functions with 'interrupt' attribute cannot be called directly.
6749 if (FDecl
->hasAttr
<AnyX86InterruptAttr
>()) {
6750 Diag(Fn
->getExprLoc(), diag::err_anyx86_interrupt_called
);
6753 if (FDecl
->hasAttr
<ARMInterruptAttr
>()) {
6754 Diag(Fn
->getExprLoc(), diag::err_arm_interrupt_called
);
6759 // X86 interrupt handlers may only call routines with attribute
6760 // no_caller_saved_registers since there is no efficient way to
6761 // save and restore the non-GPR state.
6762 if (auto *Caller
= getCurFunctionDecl()) {
6763 if (Caller
->hasAttr
<AnyX86InterruptAttr
>() ||
6764 Caller
->hasAttr
<AnyX86NoCallerSavedRegistersAttr
>()) {
6765 const TargetInfo
&TI
= Context
.getTargetInfo();
6766 bool HasNonGPRRegisters
=
6767 TI
.hasFeature("sse") || TI
.hasFeature("x87") || TI
.hasFeature("mmx");
6768 if (HasNonGPRRegisters
&&
6769 (!FDecl
|| !FDecl
->hasAttr
<AnyX86NoCallerSavedRegistersAttr
>())) {
6770 Diag(Fn
->getExprLoc(), diag::warn_anyx86_excessive_regsave
)
6771 << (Caller
->hasAttr
<AnyX86InterruptAttr
>() ? 0 : 1);
6773 Diag(FDecl
->getLocation(), diag::note_callee_decl
) << FDecl
;
6778 // Promote the function operand.
6779 // We special-case function promotion here because we only allow promoting
6780 // builtin functions to function pointers in the callee of a call.
6784 Fn
->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn
)) {
6785 // Extract the return type from the (builtin) function pointer type.
6786 // FIXME Several builtins still have setType in
6787 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6788 // Builtins.td to ensure they are correct before removing setType calls.
6789 QualType FnPtrTy
= Context
.getPointerType(FDecl
->getType());
6790 Result
= ImpCastExprToType(Fn
, FnPtrTy
, CK_BuiltinFnToFnPtr
).get();
6791 ResultTy
= FDecl
->getCallResultType();
6793 Result
= CallExprUnaryConversions(Fn
);
6794 ResultTy
= Context
.BoolTy
;
6796 if (Result
.isInvalid())
6800 // Check for a valid function type, but only if it is not a builtin which
6801 // requires custom type checking. These will be handled by
6802 // CheckBuiltinFunctionCall below just after creation of the call expression.
6803 const FunctionType
*FuncT
= nullptr;
6804 if (!BuiltinID
|| !Context
.BuiltinInfo
.hasCustomTypechecking(BuiltinID
)) {
6806 if (const PointerType
*PT
= Fn
->getType()->getAs
<PointerType
>()) {
6807 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6808 // have type pointer to function".
6809 FuncT
= PT
->getPointeeType()->getAs
<FunctionType
>();
6811 return ExprError(Diag(LParenLoc
, diag::err_typecheck_call_not_function
)
6812 << Fn
->getType() << Fn
->getSourceRange());
6813 } else if (const BlockPointerType
*BPT
=
6814 Fn
->getType()->getAs
<BlockPointerType
>()) {
6815 FuncT
= BPT
->getPointeeType()->castAs
<FunctionType
>();
6817 // Handle calls to expressions of unknown-any type.
6818 if (Fn
->getType() == Context
.UnknownAnyTy
) {
6819 ExprResult rewrite
= rebuildUnknownAnyFunction(*this, Fn
);
6820 if (rewrite
.isInvalid())
6826 return ExprError(Diag(LParenLoc
, diag::err_typecheck_call_not_function
)
6827 << Fn
->getType() << Fn
->getSourceRange());
6831 // Get the number of parameters in the function prototype, if any.
6832 // We will allocate space for max(Args.size(), NumParams) arguments
6833 // in the call expression.
6834 const auto *Proto
= dyn_cast_or_null
<FunctionProtoType
>(FuncT
);
6835 unsigned NumParams
= Proto
? Proto
->getNumParams() : 0;
6839 assert(UsesADL
== ADLCallKind::NotADL
&&
6840 "CUDAKernelCallExpr should not use ADL");
6841 TheCall
= CUDAKernelCallExpr::Create(Context
, Fn
, cast
<CallExpr
>(Config
),
6842 Args
, ResultTy
, VK_PRValue
, RParenLoc
,
6843 CurFPFeatureOverrides(), NumParams
);
6846 CallExpr::Create(Context
, Fn
, Args
, ResultTy
, VK_PRValue
, RParenLoc
,
6847 CurFPFeatureOverrides(), NumParams
, UsesADL
);
6850 if (!Context
.isDependenceAllowed()) {
6851 // Forget about the nulled arguments since typo correction
6852 // do not handle them well.
6853 TheCall
->shrinkNumArgs(Args
.size());
6854 // C cannot always handle TypoExpr nodes in builtin calls and direct
6855 // function calls as their argument checking don't necessarily handle
6856 // dependent types properly, so make sure any TypoExprs have been
6858 ExprResult Result
= CorrectDelayedTyposInExpr(TheCall
);
6859 if (!Result
.isUsable()) return ExprError();
6860 CallExpr
*TheOldCall
= TheCall
;
6861 TheCall
= dyn_cast
<CallExpr
>(Result
.get());
6862 bool CorrectedTypos
= TheCall
!= TheOldCall
;
6863 if (!TheCall
) return Result
;
6864 Args
= llvm::ArrayRef(TheCall
->getArgs(), TheCall
->getNumArgs());
6866 // A new call expression node was created if some typos were corrected.
6867 // However it may not have been constructed with enough storage. In this
6868 // case, rebuild the node with enough storage. The waste of space is
6869 // immaterial since this only happens when some typos were corrected.
6870 if (CorrectedTypos
&& Args
.size() < NumParams
) {
6872 TheCall
= CUDAKernelCallExpr::Create(
6873 Context
, Fn
, cast
<CallExpr
>(Config
), Args
, ResultTy
, VK_PRValue
,
6874 RParenLoc
, CurFPFeatureOverrides(), NumParams
);
6877 CallExpr::Create(Context
, Fn
, Args
, ResultTy
, VK_PRValue
, RParenLoc
,
6878 CurFPFeatureOverrides(), NumParams
, UsesADL
);
6880 // We can now handle the nulled arguments for the default arguments.
6881 TheCall
->setNumArgsUnsafe(std::max
<unsigned>(Args
.size(), NumParams
));
6884 // Bail out early if calling a builtin with custom type checking.
6885 if (BuiltinID
&& Context
.BuiltinInfo
.hasCustomTypechecking(BuiltinID
)) {
6886 ExprResult E
= CheckBuiltinFunctionCall(FDecl
, BuiltinID
, TheCall
);
6887 if (!E
.isInvalid() && Context
.BuiltinInfo
.isImmediate(BuiltinID
))
6888 E
= CheckForImmediateInvocation(E
, FDecl
);
6892 if (getLangOpts().CUDA
) {
6894 // CUDA: Kernel calls must be to global functions
6895 if (FDecl
&& !FDecl
->hasAttr
<CUDAGlobalAttr
>())
6896 return ExprError(Diag(LParenLoc
,diag::err_kern_call_not_global_function
)
6897 << FDecl
<< Fn
->getSourceRange());
6899 // CUDA: Kernel function must have 'void' return type
6900 if (!FuncT
->getReturnType()->isVoidType() &&
6901 !FuncT
->getReturnType()->getAs
<AutoType
>() &&
6902 !FuncT
->getReturnType()->isInstantiationDependentType())
6903 return ExprError(Diag(LParenLoc
, diag::err_kern_type_not_void_return
)
6904 << Fn
->getType() << Fn
->getSourceRange());
6906 // CUDA: Calls to global functions must be configured
6907 if (FDecl
&& FDecl
->hasAttr
<CUDAGlobalAttr
>())
6908 return ExprError(Diag(LParenLoc
, diag::err_global_call_not_config
)
6909 << FDecl
<< Fn
->getSourceRange());
6913 // Check for a valid return type
6914 if (CheckCallReturnType(FuncT
->getReturnType(), Fn
->getBeginLoc(), TheCall
,
6918 // We know the result type of the call, set it.
6919 TheCall
->setType(FuncT
->getCallResultType(Context
));
6920 TheCall
->setValueKind(Expr::getValueKindForType(FuncT
->getReturnType()));
6922 // WebAssembly tables can't be used as arguments.
6923 if (Context
.getTargetInfo().getTriple().isWasm()) {
6924 for (const Expr
*Arg
: Args
) {
6925 if (Arg
&& Arg
->getType()->isWebAssemblyTableType()) {
6926 return ExprError(Diag(Arg
->getExprLoc(),
6927 diag::err_wasm_table_as_function_parameter
));
6933 if (ConvertArgumentsForCall(TheCall
, Fn
, FDecl
, Proto
, Args
, RParenLoc
,
6937 assert(isa
<FunctionNoProtoType
>(FuncT
) && "Unknown FunctionType!");
6940 // Check if we have too few/too many template arguments, based
6941 // on our knowledge of the function definition.
6942 const FunctionDecl
*Def
= nullptr;
6943 if (FDecl
->hasBody(Def
) && Args
.size() != Def
->param_size()) {
6944 Proto
= Def
->getType()->getAs
<FunctionProtoType
>();
6945 if (!Proto
|| !(Proto
->isVariadic() && Args
.size() >= Def
->param_size()))
6946 Diag(RParenLoc
, diag::warn_call_wrong_number_of_arguments
)
6947 << (Args
.size() > Def
->param_size()) << FDecl
<< Fn
->getSourceRange();
6950 // If the function we're calling isn't a function prototype, but we have
6951 // a function prototype from a prior declaratiom, use that prototype.
6952 if (!FDecl
->hasPrototype())
6953 Proto
= FDecl
->getType()->getAs
<FunctionProtoType
>();
6956 // If we still haven't found a prototype to use but there are arguments to
6957 // the call, diagnose this as calling a function without a prototype.
6958 // However, if we found a function declaration, check to see if
6959 // -Wdeprecated-non-prototype was disabled where the function was declared.
6960 // If so, we will silence the diagnostic here on the assumption that this
6961 // interface is intentional and the user knows what they're doing. We will
6962 // also silence the diagnostic if there is a function declaration but it
6963 // was implicitly defined (the user already gets diagnostics about the
6964 // creation of the implicit function declaration, so the additional warning
6966 if (!Proto
&& !Args
.empty() &&
6967 (!FDecl
|| (!FDecl
->isImplicit() &&
6968 !Diags
.isIgnored(diag::warn_strict_uses_without_prototype
,
6969 FDecl
->getLocation()))))
6970 Diag(LParenLoc
, diag::warn_strict_uses_without_prototype
)
6971 << (FDecl
!= nullptr) << FDecl
;
6973 // Promote the arguments (C99 6.5.2.2p6).
6974 for (unsigned i
= 0, e
= Args
.size(); i
!= e
; i
++) {
6975 Expr
*Arg
= Args
[i
];
6977 if (Proto
&& i
< Proto
->getNumParams()) {
6978 InitializedEntity Entity
= InitializedEntity::InitializeParameter(
6979 Context
, Proto
->getParamType(i
), Proto
->isParamConsumed(i
));
6981 PerformCopyInitialization(Entity
, SourceLocation(), Arg
);
6982 if (ArgE
.isInvalid())
6985 Arg
= ArgE
.getAs
<Expr
>();
6988 ExprResult ArgE
= DefaultArgumentPromotion(Arg
);
6990 if (ArgE
.isInvalid())
6993 Arg
= ArgE
.getAs
<Expr
>();
6996 if (RequireCompleteType(Arg
->getBeginLoc(), Arg
->getType(),
6997 diag::err_call_incomplete_argument
, Arg
))
7000 TheCall
->setArg(i
, Arg
);
7002 TheCall
->computeDependence();
7005 if (CXXMethodDecl
*Method
= dyn_cast_or_null
<CXXMethodDecl
>(FDecl
))
7006 if (Method
->isImplicitObjectMemberFunction())
7007 return ExprError(Diag(LParenLoc
, diag::err_member_call_without_object
)
7008 << Fn
->getSourceRange() << 0);
7010 // Check for sentinels
7012 DiagnoseSentinelCalls(NDecl
, LParenLoc
, Args
);
7014 // Warn for unions passing across security boundary (CMSE).
7015 if (FuncT
!= nullptr && FuncT
->getCmseNSCallAttr()) {
7016 for (unsigned i
= 0, e
= Args
.size(); i
!= e
; i
++) {
7017 if (const auto *RT
=
7018 dyn_cast
<RecordType
>(Args
[i
]->getType().getCanonicalType())) {
7019 if (RT
->getDecl()->isOrContainsUnion())
7020 Diag(Args
[i
]->getBeginLoc(), diag::warn_cmse_nonsecure_union
)
7026 // Do special checking on direct calls to functions.
7028 if (CheckFunctionCall(FDecl
, TheCall
, Proto
))
7031 checkFortifiedBuiltinMemoryFunction(FDecl
, TheCall
);
7034 return CheckBuiltinFunctionCall(FDecl
, BuiltinID
, TheCall
);
7036 if (CheckPointerCall(NDecl
, TheCall
, Proto
))
7039 if (CheckOtherCall(TheCall
, Proto
))
7043 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall
), FDecl
);
7047 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc
, ParsedType Ty
,
7048 SourceLocation RParenLoc
, Expr
*InitExpr
) {
7049 assert(Ty
&& "ActOnCompoundLiteral(): missing type");
7050 assert(InitExpr
&& "ActOnCompoundLiteral(): missing expression");
7052 TypeSourceInfo
*TInfo
;
7053 QualType literalType
= GetTypeFromParser(Ty
, &TInfo
);
7055 TInfo
= Context
.getTrivialTypeSourceInfo(literalType
);
7057 return BuildCompoundLiteralExpr(LParenLoc
, TInfo
, RParenLoc
, InitExpr
);
7061 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc
, TypeSourceInfo
*TInfo
,
7062 SourceLocation RParenLoc
, Expr
*LiteralExpr
) {
7063 QualType literalType
= TInfo
->getType();
7065 if (literalType
->isArrayType()) {
7066 if (RequireCompleteSizedType(
7067 LParenLoc
, Context
.getBaseElementType(literalType
),
7068 diag::err_array_incomplete_or_sizeless_type
,
7069 SourceRange(LParenLoc
, LiteralExpr
->getSourceRange().getEnd())))
7071 if (literalType
->isVariableArrayType()) {
7072 // C23 6.7.10p4: An entity of variable length array type shall not be
7073 // initialized except by an empty initializer.
7075 // The C extension warnings are issued from ParseBraceInitializer() and
7076 // do not need to be issued here. However, we continue to issue an error
7077 // in the case there are initializers or we are compiling C++. We allow
7078 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7079 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7080 // FIXME: should we allow this construct in C++ when it makes sense to do
7083 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7084 // shall specify an object type or an array of unknown size, but not a
7085 // variable length array type. This seems odd, as it allows 'int a[size] =
7086 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7087 // says, this is what's implemented here for C (except for the extension
7088 // that permits constant foldable size arrays)
7090 auto diagID
= LangOpts
.CPlusPlus
7091 ? diag::err_variable_object_no_init
7092 : diag::err_compound_literal_with_vla_type
;
7093 if (!tryToFixVariablyModifiedVarType(TInfo
, literalType
, LParenLoc
,
7097 } else if (!literalType
->isDependentType() &&
7098 RequireCompleteType(LParenLoc
, literalType
,
7099 diag::err_typecheck_decl_incomplete_type
,
7100 SourceRange(LParenLoc
, LiteralExpr
->getSourceRange().getEnd())))
7103 InitializedEntity Entity
7104 = InitializedEntity::InitializeCompoundLiteralInit(TInfo
);
7105 InitializationKind Kind
7106 = InitializationKind::CreateCStyleCast(LParenLoc
,
7107 SourceRange(LParenLoc
, RParenLoc
),
7109 InitializationSequence
InitSeq(*this, Entity
, Kind
, LiteralExpr
);
7110 ExprResult Result
= InitSeq
.Perform(*this, Entity
, Kind
, LiteralExpr
,
7112 if (Result
.isInvalid())
7114 LiteralExpr
= Result
.get();
7116 bool isFileScope
= !CurContext
->isFunctionOrMethod();
7118 // In C, compound literals are l-values for some reason.
7119 // For GCC compatibility, in C++, file-scope array compound literals with
7120 // constant initializers are also l-values, and compound literals are
7121 // otherwise prvalues.
7123 // (GCC also treats C++ list-initialized file-scope array prvalues with
7124 // constant initializers as l-values, but that's non-conforming, so we don't
7125 // follow it there.)
7127 // FIXME: It would be better to handle the lvalue cases as materializing and
7128 // lifetime-extending a temporary object, but our materialized temporaries
7129 // representation only supports lifetime extension from a variable, not "out
7131 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7132 // is bound to the result of applying array-to-pointer decay to the compound
7134 // FIXME: GCC supports compound literals of reference type, which should
7135 // obviously have a value kind derived from the kind of reference involved.
7137 (getLangOpts().CPlusPlus
&& !(isFileScope
&& literalType
->isArrayType()))
7142 if (auto ILE
= dyn_cast
<InitListExpr
>(LiteralExpr
))
7143 for (unsigned i
= 0, j
= ILE
->getNumInits(); i
!= j
; i
++) {
7144 Expr
*Init
= ILE
->getInit(i
);
7145 ILE
->setInit(i
, ConstantExpr::Create(Context
, Init
));
7148 auto *E
= new (Context
) CompoundLiteralExpr(LParenLoc
, TInfo
, literalType
,
7149 VK
, LiteralExpr
, isFileScope
);
7151 if (!LiteralExpr
->isTypeDependent() &&
7152 !LiteralExpr
->isValueDependent() &&
7153 !literalType
->isDependentType()) // C99 6.5.2.5p3
7154 if (CheckForConstantInitializer(LiteralExpr
))
7156 } else if (literalType
.getAddressSpace() != LangAS::opencl_private
&&
7157 literalType
.getAddressSpace() != LangAS::Default
) {
7158 // Embedded-C extensions to C99 6.5.2.5:
7159 // "If the compound literal occurs inside the body of a function, the
7160 // type name shall not be qualified by an address-space qualifier."
7161 Diag(LParenLoc
, diag::err_compound_literal_with_address_space
)
7162 << SourceRange(LParenLoc
, LiteralExpr
->getSourceRange().getEnd());
7166 if (!isFileScope
&& !getLangOpts().CPlusPlus
) {
7167 // Compound literals that have automatic storage duration are destroyed at
7168 // the end of the scope in C; in C++, they're just temporaries.
7170 // Emit diagnostics if it is or contains a C union type that is non-trivial
7172 if (E
->getType().hasNonTrivialToPrimitiveDestructCUnion())
7173 checkNonTrivialCUnion(E
->getType(), E
->getExprLoc(),
7174 NTCUC_CompoundLiteral
, NTCUK_Destruct
);
7176 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7177 if (literalType
.isDestructedType()) {
7178 Cleanup
.setExprNeedsCleanups(true);
7179 ExprCleanupObjects
.push_back(E
);
7180 getCurFunction()->setHasBranchProtectedScope();
7184 if (E
->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7185 E
->getType().hasNonTrivialToPrimitiveCopyCUnion())
7186 checkNonTrivialCUnionInInitializer(E
->getInitializer(),
7187 E
->getInitializer()->getExprLoc());
7189 return MaybeBindToTemporary(E
);
7193 Sema::ActOnInitList(SourceLocation LBraceLoc
, MultiExprArg InitArgList
,
7194 SourceLocation RBraceLoc
) {
7195 // Only produce each kind of designated initialization diagnostic once.
7196 SourceLocation FirstDesignator
;
7197 bool DiagnosedArrayDesignator
= false;
7198 bool DiagnosedNestedDesignator
= false;
7199 bool DiagnosedMixedDesignator
= false;
7201 // Check that any designated initializers are syntactically valid in the
7202 // current language mode.
7203 for (unsigned I
= 0, E
= InitArgList
.size(); I
!= E
; ++I
) {
7204 if (auto *DIE
= dyn_cast
<DesignatedInitExpr
>(InitArgList
[I
])) {
7205 if (FirstDesignator
.isInvalid())
7206 FirstDesignator
= DIE
->getBeginLoc();
7208 if (!getLangOpts().CPlusPlus
)
7211 if (!DiagnosedNestedDesignator
&& DIE
->size() > 1) {
7212 DiagnosedNestedDesignator
= true;
7213 Diag(DIE
->getBeginLoc(), diag::ext_designated_init_nested
)
7214 << DIE
->getDesignatorsSourceRange();
7217 for (auto &Desig
: DIE
->designators()) {
7218 if (!Desig
.isFieldDesignator() && !DiagnosedArrayDesignator
) {
7219 DiagnosedArrayDesignator
= true;
7220 Diag(Desig
.getBeginLoc(), diag::ext_designated_init_array
)
7221 << Desig
.getSourceRange();
7225 if (!DiagnosedMixedDesignator
&&
7226 !isa
<DesignatedInitExpr
>(InitArgList
[0])) {
7227 DiagnosedMixedDesignator
= true;
7228 Diag(DIE
->getBeginLoc(), diag::ext_designated_init_mixed
)
7229 << DIE
->getSourceRange();
7230 Diag(InitArgList
[0]->getBeginLoc(), diag::note_designated_init_mixed
)
7231 << InitArgList
[0]->getSourceRange();
7233 } else if (getLangOpts().CPlusPlus
&& !DiagnosedMixedDesignator
&&
7234 isa
<DesignatedInitExpr
>(InitArgList
[0])) {
7235 DiagnosedMixedDesignator
= true;
7236 auto *DIE
= cast
<DesignatedInitExpr
>(InitArgList
[0]);
7237 Diag(DIE
->getBeginLoc(), diag::ext_designated_init_mixed
)
7238 << DIE
->getSourceRange();
7239 Diag(InitArgList
[I
]->getBeginLoc(), diag::note_designated_init_mixed
)
7240 << InitArgList
[I
]->getSourceRange();
7244 if (FirstDesignator
.isValid()) {
7245 // Only diagnose designated initiaization as a C++20 extension if we didn't
7246 // already diagnose use of (non-C++20) C99 designator syntax.
7247 if (getLangOpts().CPlusPlus
&& !DiagnosedArrayDesignator
&&
7248 !DiagnosedNestedDesignator
&& !DiagnosedMixedDesignator
) {
7249 Diag(FirstDesignator
, getLangOpts().CPlusPlus20
7250 ? diag::warn_cxx17_compat_designated_init
7251 : diag::ext_cxx_designated_init
);
7252 } else if (!getLangOpts().CPlusPlus
&& !getLangOpts().C99
) {
7253 Diag(FirstDesignator
, diag::ext_designated_init
);
7257 return BuildInitList(LBraceLoc
, InitArgList
, RBraceLoc
);
7261 Sema::BuildInitList(SourceLocation LBraceLoc
, MultiExprArg InitArgList
,
7262 SourceLocation RBraceLoc
) {
7263 // Semantic analysis for initializers is done by ActOnDeclarator() and
7264 // CheckInitializer() - it requires knowledge of the object being initialized.
7266 // Immediately handle non-overload placeholders. Overloads can be
7267 // resolved contextually, but everything else here can't.
7268 for (unsigned I
= 0, E
= InitArgList
.size(); I
!= E
; ++I
) {
7269 if (InitArgList
[I
]->getType()->isNonOverloadPlaceholderType()) {
7270 ExprResult result
= CheckPlaceholderExpr(InitArgList
[I
]);
7272 // Ignore failures; dropping the entire initializer list because
7273 // of one failure would be terrible for indexing/etc.
7274 if (result
.isInvalid()) continue;
7276 InitArgList
[I
] = result
.get();
7281 new (Context
) InitListExpr(Context
, LBraceLoc
, InitArgList
, RBraceLoc
);
7282 E
->setType(Context
.VoidTy
); // FIXME: just a place holder for now.
7286 void Sema::maybeExtendBlockObject(ExprResult
&E
) {
7287 assert(E
.get()->getType()->isBlockPointerType());
7288 assert(E
.get()->isPRValue());
7290 // Only do this in an r-value context.
7291 if (!getLangOpts().ObjCAutoRefCount
) return;
7293 E
= ImplicitCastExpr::Create(
7294 Context
, E
.get()->getType(), CK_ARCExtendBlockObject
, E
.get(),
7295 /*base path*/ nullptr, VK_PRValue
, FPOptionsOverride());
7296 Cleanup
.setExprNeedsCleanups(true);
7299 CastKind
Sema::PrepareScalarCast(ExprResult
&Src
, QualType DestTy
) {
7300 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7301 // Also, callers should have filtered out the invalid cases with
7302 // pointers. Everything else should be possible.
7304 QualType SrcTy
= Src
.get()->getType();
7305 if (Context
.hasSameUnqualifiedType(SrcTy
, DestTy
))
7308 switch (Type::ScalarTypeKind SrcKind
= SrcTy
->getScalarTypeKind()) {
7309 case Type::STK_MemberPointer
:
7310 llvm_unreachable("member pointer type in C");
7312 case Type::STK_CPointer
:
7313 case Type::STK_BlockPointer
:
7314 case Type::STK_ObjCObjectPointer
:
7315 switch (DestTy
->getScalarTypeKind()) {
7316 case Type::STK_CPointer
: {
7317 LangAS SrcAS
= SrcTy
->getPointeeType().getAddressSpace();
7318 LangAS DestAS
= DestTy
->getPointeeType().getAddressSpace();
7319 if (SrcAS
!= DestAS
)
7320 return CK_AddressSpaceConversion
;
7321 if (Context
.hasCvrSimilarType(SrcTy
, DestTy
))
7325 case Type::STK_BlockPointer
:
7326 return (SrcKind
== Type::STK_BlockPointer
7327 ? CK_BitCast
: CK_AnyPointerToBlockPointerCast
);
7328 case Type::STK_ObjCObjectPointer
:
7329 if (SrcKind
== Type::STK_ObjCObjectPointer
)
7331 if (SrcKind
== Type::STK_CPointer
)
7332 return CK_CPointerToObjCPointerCast
;
7333 maybeExtendBlockObject(Src
);
7334 return CK_BlockPointerToObjCPointerCast
;
7335 case Type::STK_Bool
:
7336 return CK_PointerToBoolean
;
7337 case Type::STK_Integral
:
7338 return CK_PointerToIntegral
;
7339 case Type::STK_Floating
:
7340 case Type::STK_FloatingComplex
:
7341 case Type::STK_IntegralComplex
:
7342 case Type::STK_MemberPointer
:
7343 case Type::STK_FixedPoint
:
7344 llvm_unreachable("illegal cast from pointer");
7346 llvm_unreachable("Should have returned before this");
7348 case Type::STK_FixedPoint
:
7349 switch (DestTy
->getScalarTypeKind()) {
7350 case Type::STK_FixedPoint
:
7351 return CK_FixedPointCast
;
7352 case Type::STK_Bool
:
7353 return CK_FixedPointToBoolean
;
7354 case Type::STK_Integral
:
7355 return CK_FixedPointToIntegral
;
7356 case Type::STK_Floating
:
7357 return CK_FixedPointToFloating
;
7358 case Type::STK_IntegralComplex
:
7359 case Type::STK_FloatingComplex
:
7360 Diag(Src
.get()->getExprLoc(),
7361 diag::err_unimplemented_conversion_with_fixed_point_type
)
7363 return CK_IntegralCast
;
7364 case Type::STK_CPointer
:
7365 case Type::STK_ObjCObjectPointer
:
7366 case Type::STK_BlockPointer
:
7367 case Type::STK_MemberPointer
:
7368 llvm_unreachable("illegal cast to pointer type");
7370 llvm_unreachable("Should have returned before this");
7372 case Type::STK_Bool
: // casting from bool is like casting from an integer
7373 case Type::STK_Integral
:
7374 switch (DestTy
->getScalarTypeKind()) {
7375 case Type::STK_CPointer
:
7376 case Type::STK_ObjCObjectPointer
:
7377 case Type::STK_BlockPointer
:
7378 if (Src
.get()->isNullPointerConstant(Context
,
7379 Expr::NPC_ValueDependentIsNull
))
7380 return CK_NullToPointer
;
7381 return CK_IntegralToPointer
;
7382 case Type::STK_Bool
:
7383 return CK_IntegralToBoolean
;
7384 case Type::STK_Integral
:
7385 return CK_IntegralCast
;
7386 case Type::STK_Floating
:
7387 return CK_IntegralToFloating
;
7388 case Type::STK_IntegralComplex
:
7389 Src
= ImpCastExprToType(Src
.get(),
7390 DestTy
->castAs
<ComplexType
>()->getElementType(),
7392 return CK_IntegralRealToComplex
;
7393 case Type::STK_FloatingComplex
:
7394 Src
= ImpCastExprToType(Src
.get(),
7395 DestTy
->castAs
<ComplexType
>()->getElementType(),
7396 CK_IntegralToFloating
);
7397 return CK_FloatingRealToComplex
;
7398 case Type::STK_MemberPointer
:
7399 llvm_unreachable("member pointer type in C");
7400 case Type::STK_FixedPoint
:
7401 return CK_IntegralToFixedPoint
;
7403 llvm_unreachable("Should have returned before this");
7405 case Type::STK_Floating
:
7406 switch (DestTy
->getScalarTypeKind()) {
7407 case Type::STK_Floating
:
7408 return CK_FloatingCast
;
7409 case Type::STK_Bool
:
7410 return CK_FloatingToBoolean
;
7411 case Type::STK_Integral
:
7412 return CK_FloatingToIntegral
;
7413 case Type::STK_FloatingComplex
:
7414 Src
= ImpCastExprToType(Src
.get(),
7415 DestTy
->castAs
<ComplexType
>()->getElementType(),
7417 return CK_FloatingRealToComplex
;
7418 case Type::STK_IntegralComplex
:
7419 Src
= ImpCastExprToType(Src
.get(),
7420 DestTy
->castAs
<ComplexType
>()->getElementType(),
7421 CK_FloatingToIntegral
);
7422 return CK_IntegralRealToComplex
;
7423 case Type::STK_CPointer
:
7424 case Type::STK_ObjCObjectPointer
:
7425 case Type::STK_BlockPointer
:
7426 llvm_unreachable("valid float->pointer cast?");
7427 case Type::STK_MemberPointer
:
7428 llvm_unreachable("member pointer type in C");
7429 case Type::STK_FixedPoint
:
7430 return CK_FloatingToFixedPoint
;
7432 llvm_unreachable("Should have returned before this");
7434 case Type::STK_FloatingComplex
:
7435 switch (DestTy
->getScalarTypeKind()) {
7436 case Type::STK_FloatingComplex
:
7437 return CK_FloatingComplexCast
;
7438 case Type::STK_IntegralComplex
:
7439 return CK_FloatingComplexToIntegralComplex
;
7440 case Type::STK_Floating
: {
7441 QualType ET
= SrcTy
->castAs
<ComplexType
>()->getElementType();
7442 if (Context
.hasSameType(ET
, DestTy
))
7443 return CK_FloatingComplexToReal
;
7444 Src
= ImpCastExprToType(Src
.get(), ET
, CK_FloatingComplexToReal
);
7445 return CK_FloatingCast
;
7447 case Type::STK_Bool
:
7448 return CK_FloatingComplexToBoolean
;
7449 case Type::STK_Integral
:
7450 Src
= ImpCastExprToType(Src
.get(),
7451 SrcTy
->castAs
<ComplexType
>()->getElementType(),
7452 CK_FloatingComplexToReal
);
7453 return CK_FloatingToIntegral
;
7454 case Type::STK_CPointer
:
7455 case Type::STK_ObjCObjectPointer
:
7456 case Type::STK_BlockPointer
:
7457 llvm_unreachable("valid complex float->pointer cast?");
7458 case Type::STK_MemberPointer
:
7459 llvm_unreachable("member pointer type in C");
7460 case Type::STK_FixedPoint
:
7461 Diag(Src
.get()->getExprLoc(),
7462 diag::err_unimplemented_conversion_with_fixed_point_type
)
7464 return CK_IntegralCast
;
7466 llvm_unreachable("Should have returned before this");
7468 case Type::STK_IntegralComplex
:
7469 switch (DestTy
->getScalarTypeKind()) {
7470 case Type::STK_FloatingComplex
:
7471 return CK_IntegralComplexToFloatingComplex
;
7472 case Type::STK_IntegralComplex
:
7473 return CK_IntegralComplexCast
;
7474 case Type::STK_Integral
: {
7475 QualType ET
= SrcTy
->castAs
<ComplexType
>()->getElementType();
7476 if (Context
.hasSameType(ET
, DestTy
))
7477 return CK_IntegralComplexToReal
;
7478 Src
= ImpCastExprToType(Src
.get(), ET
, CK_IntegralComplexToReal
);
7479 return CK_IntegralCast
;
7481 case Type::STK_Bool
:
7482 return CK_IntegralComplexToBoolean
;
7483 case Type::STK_Floating
:
7484 Src
= ImpCastExprToType(Src
.get(),
7485 SrcTy
->castAs
<ComplexType
>()->getElementType(),
7486 CK_IntegralComplexToReal
);
7487 return CK_IntegralToFloating
;
7488 case Type::STK_CPointer
:
7489 case Type::STK_ObjCObjectPointer
:
7490 case Type::STK_BlockPointer
:
7491 llvm_unreachable("valid complex int->pointer cast?");
7492 case Type::STK_MemberPointer
:
7493 llvm_unreachable("member pointer type in C");
7494 case Type::STK_FixedPoint
:
7495 Diag(Src
.get()->getExprLoc(),
7496 diag::err_unimplemented_conversion_with_fixed_point_type
)
7498 return CK_IntegralCast
;
7500 llvm_unreachable("Should have returned before this");
7503 llvm_unreachable("Unhandled scalar cast");
7506 static bool breakDownVectorType(QualType type
, uint64_t &len
,
7507 QualType
&eltType
) {
7508 // Vectors are simple.
7509 if (const VectorType
*vecType
= type
->getAs
<VectorType
>()) {
7510 len
= vecType
->getNumElements();
7511 eltType
= vecType
->getElementType();
7512 assert(eltType
->isScalarType());
7516 // We allow lax conversion to and from non-vector types, but only if
7517 // they're real types (i.e. non-complex, non-pointer scalar types).
7518 if (!type
->isRealType()) return false;
7525 bool Sema::isValidSveBitcast(QualType srcTy
, QualType destTy
) {
7526 assert(srcTy
->isVectorType() || destTy
->isVectorType());
7528 auto ValidScalableConversion
= [](QualType FirstType
, QualType SecondType
) {
7529 if (!FirstType
->isSVESizelessBuiltinType())
7532 const auto *VecTy
= SecondType
->getAs
<VectorType
>();
7533 return VecTy
&& VecTy
->getVectorKind() == VectorKind::SveFixedLengthData
;
7536 return ValidScalableConversion(srcTy
, destTy
) ||
7537 ValidScalableConversion(destTy
, srcTy
);
7540 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy
, QualType destTy
) {
7541 if (!destTy
->isMatrixType() || !srcTy
->isMatrixType())
7544 const ConstantMatrixType
*matSrcType
= srcTy
->getAs
<ConstantMatrixType
>();
7545 const ConstantMatrixType
*matDestType
= destTy
->getAs
<ConstantMatrixType
>();
7547 return matSrcType
->getNumRows() == matDestType
->getNumRows() &&
7548 matSrcType
->getNumColumns() == matDestType
->getNumColumns();
7551 bool Sema::areVectorTypesSameSize(QualType SrcTy
, QualType DestTy
) {
7552 assert(DestTy
->isVectorType() || SrcTy
->isVectorType());
7554 uint64_t SrcLen
, DestLen
;
7555 QualType SrcEltTy
, DestEltTy
;
7556 if (!breakDownVectorType(SrcTy
, SrcLen
, SrcEltTy
))
7558 if (!breakDownVectorType(DestTy
, DestLen
, DestEltTy
))
7561 // ASTContext::getTypeSize will return the size rounded up to a
7562 // power of 2, so instead of using that, we need to use the raw
7563 // element size multiplied by the element count.
7564 uint64_t SrcEltSize
= Context
.getTypeSize(SrcEltTy
);
7565 uint64_t DestEltSize
= Context
.getTypeSize(DestEltTy
);
7567 return (SrcLen
* SrcEltSize
== DestLen
* DestEltSize
);
7570 bool Sema::anyAltivecTypes(QualType SrcTy
, QualType DestTy
) {
7571 assert((DestTy
->isVectorType() || SrcTy
->isVectorType()) &&
7572 "expected at least one type to be a vector here");
7574 bool IsSrcTyAltivec
=
7575 SrcTy
->isVectorType() && ((SrcTy
->castAs
<VectorType
>()->getVectorKind() ==
7576 VectorKind::AltiVecVector
) ||
7577 (SrcTy
->castAs
<VectorType
>()->getVectorKind() ==
7578 VectorKind::AltiVecBool
) ||
7579 (SrcTy
->castAs
<VectorType
>()->getVectorKind() ==
7580 VectorKind::AltiVecPixel
));
7582 bool IsDestTyAltivec
= DestTy
->isVectorType() &&
7583 ((DestTy
->castAs
<VectorType
>()->getVectorKind() ==
7584 VectorKind::AltiVecVector
) ||
7585 (DestTy
->castAs
<VectorType
>()->getVectorKind() ==
7586 VectorKind::AltiVecBool
) ||
7587 (DestTy
->castAs
<VectorType
>()->getVectorKind() ==
7588 VectorKind::AltiVecPixel
));
7590 return (IsSrcTyAltivec
|| IsDestTyAltivec
);
7593 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy
, QualType destTy
) {
7594 assert(destTy
->isVectorType() || srcTy
->isVectorType());
7596 // Disallow lax conversions between scalars and ExtVectors (these
7597 // conversions are allowed for other vector types because common headers
7598 // depend on them). Most scalar OP ExtVector cases are handled by the
7599 // splat path anyway, which does what we want (convert, not bitcast).
7600 // What this rules out for ExtVectors is crazy things like char4*float.
7601 if (srcTy
->isScalarType() && destTy
->isExtVectorType()) return false;
7602 if (destTy
->isScalarType() && srcTy
->isExtVectorType()) return false;
7604 return areVectorTypesSameSize(srcTy
, destTy
);
7607 bool Sema::isLaxVectorConversion(QualType srcTy
, QualType destTy
) {
7608 assert(destTy
->isVectorType() || srcTy
->isVectorType());
7610 switch (Context
.getLangOpts().getLaxVectorConversions()) {
7611 case LangOptions::LaxVectorConversionKind::None
:
7614 case LangOptions::LaxVectorConversionKind::Integer
:
7615 if (!srcTy
->isIntegralOrEnumerationType()) {
7616 auto *Vec
= srcTy
->getAs
<VectorType
>();
7617 if (!Vec
|| !Vec
->getElementType()->isIntegralOrEnumerationType())
7620 if (!destTy
->isIntegralOrEnumerationType()) {
7621 auto *Vec
= destTy
->getAs
<VectorType
>();
7622 if (!Vec
|| !Vec
->getElementType()->isIntegralOrEnumerationType())
7625 // OK, integer (vector) -> integer (vector) bitcast.
7628 case LangOptions::LaxVectorConversionKind::All
:
7632 return areLaxCompatibleVectorTypes(srcTy
, destTy
);
7635 bool Sema::CheckMatrixCast(SourceRange R
, QualType DestTy
, QualType SrcTy
,
7637 if (SrcTy
->isMatrixType() && DestTy
->isMatrixType()) {
7638 if (!areMatrixTypesOfTheSameDimension(SrcTy
, DestTy
)) {
7639 return Diag(R
.getBegin(), diag::err_invalid_conversion_between_matrixes
)
7640 << DestTy
<< SrcTy
<< R
;
7642 } else if (SrcTy
->isMatrixType()) {
7643 return Diag(R
.getBegin(),
7644 diag::err_invalid_conversion_between_matrix_and_type
)
7645 << SrcTy
<< DestTy
<< R
;
7646 } else if (DestTy
->isMatrixType()) {
7647 return Diag(R
.getBegin(),
7648 diag::err_invalid_conversion_between_matrix_and_type
)
7649 << DestTy
<< SrcTy
<< R
;
7652 Kind
= CK_MatrixCast
;
7656 bool Sema::CheckVectorCast(SourceRange R
, QualType VectorTy
, QualType Ty
,
7658 assert(VectorTy
->isVectorType() && "Not a vector type!");
7660 if (Ty
->isVectorType() || Ty
->isIntegralType(Context
)) {
7661 if (!areLaxCompatibleVectorTypes(Ty
, VectorTy
))
7662 return Diag(R
.getBegin(),
7663 Ty
->isVectorType() ?
7664 diag::err_invalid_conversion_between_vectors
:
7665 diag::err_invalid_conversion_between_vector_and_integer
)
7666 << VectorTy
<< Ty
<< R
;
7668 return Diag(R
.getBegin(),
7669 diag::err_invalid_conversion_between_vector_and_scalar
)
7670 << VectorTy
<< Ty
<< R
;
7676 ExprResult
Sema::prepareVectorSplat(QualType VectorTy
, Expr
*SplattedExpr
) {
7677 QualType DestElemTy
= VectorTy
->castAs
<VectorType
>()->getElementType();
7679 if (DestElemTy
== SplattedExpr
->getType())
7680 return SplattedExpr
;
7682 assert(DestElemTy
->isFloatingType() ||
7683 DestElemTy
->isIntegralOrEnumerationType());
7686 if (VectorTy
->isExtVectorType() && SplattedExpr
->getType()->isBooleanType()) {
7687 // OpenCL requires that we convert `true` boolean expressions to -1, but
7688 // only when splatting vectors.
7689 if (DestElemTy
->isFloatingType()) {
7690 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7691 // in two steps: boolean to signed integral, then to floating.
7692 ExprResult CastExprRes
= ImpCastExprToType(SplattedExpr
, Context
.IntTy
,
7693 CK_BooleanToSignedIntegral
);
7694 SplattedExpr
= CastExprRes
.get();
7695 CK
= CK_IntegralToFloating
;
7697 CK
= CK_BooleanToSignedIntegral
;
7700 ExprResult CastExprRes
= SplattedExpr
;
7701 CK
= PrepareScalarCast(CastExprRes
, DestElemTy
);
7702 if (CastExprRes
.isInvalid())
7704 SplattedExpr
= CastExprRes
.get();
7706 return ImpCastExprToType(SplattedExpr
, DestElemTy
, CK
);
7709 ExprResult
Sema::CheckExtVectorCast(SourceRange R
, QualType DestTy
,
7710 Expr
*CastExpr
, CastKind
&Kind
) {
7711 assert(DestTy
->isExtVectorType() && "Not an extended vector type!");
7713 QualType SrcTy
= CastExpr
->getType();
7715 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7716 // an ExtVectorType.
7717 // In OpenCL, casts between vectors of different types are not allowed.
7718 // (See OpenCL 6.2).
7719 if (SrcTy
->isVectorType()) {
7720 if (!areLaxCompatibleVectorTypes(SrcTy
, DestTy
) ||
7721 (getLangOpts().OpenCL
&&
7722 !Context
.hasSameUnqualifiedType(DestTy
, SrcTy
))) {
7723 Diag(R
.getBegin(),diag::err_invalid_conversion_between_ext_vectors
)
7724 << DestTy
<< SrcTy
<< R
;
7731 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7732 // conversion will take place first from scalar to elt type, and then
7733 // splat from elt type to vector.
7734 if (SrcTy
->isPointerType())
7735 return Diag(R
.getBegin(),
7736 diag::err_invalid_conversion_between_vector_and_scalar
)
7737 << DestTy
<< SrcTy
<< R
;
7739 Kind
= CK_VectorSplat
;
7740 return prepareVectorSplat(DestTy
, CastExpr
);
7744 Sema::ActOnCastExpr(Scope
*S
, SourceLocation LParenLoc
,
7745 Declarator
&D
, ParsedType
&Ty
,
7746 SourceLocation RParenLoc
, Expr
*CastExpr
) {
7747 assert(!D
.isInvalidType() && (CastExpr
!= nullptr) &&
7748 "ActOnCastExpr(): missing type or expr");
7750 TypeSourceInfo
*castTInfo
= GetTypeForDeclaratorCast(D
, CastExpr
->getType());
7751 if (D
.isInvalidType())
7754 if (getLangOpts().CPlusPlus
) {
7755 // Check that there are no default arguments (C++ only).
7756 CheckExtraCXXDefaultArguments(D
);
7758 // Make sure any TypoExprs have been dealt with.
7759 ExprResult Res
= CorrectDelayedTyposInExpr(CastExpr
);
7760 if (!Res
.isUsable())
7762 CastExpr
= Res
.get();
7765 checkUnusedDeclAttributes(D
);
7767 QualType castType
= castTInfo
->getType();
7768 Ty
= CreateParsedType(castType
, castTInfo
);
7770 bool isVectorLiteral
= false;
7772 // Check for an altivec or OpenCL literal,
7773 // i.e. all the elements are integer constants.
7774 ParenExpr
*PE
= dyn_cast
<ParenExpr
>(CastExpr
);
7775 ParenListExpr
*PLE
= dyn_cast
<ParenListExpr
>(CastExpr
);
7776 if ((getLangOpts().AltiVec
|| getLangOpts().ZVector
|| getLangOpts().OpenCL
)
7777 && castType
->isVectorType() && (PE
|| PLE
)) {
7778 if (PLE
&& PLE
->getNumExprs() == 0) {
7779 Diag(PLE
->getExprLoc(), diag::err_altivec_empty_initializer
);
7782 if (PE
|| PLE
->getNumExprs() == 1) {
7783 Expr
*E
= (PE
? PE
->getSubExpr() : PLE
->getExpr(0));
7784 if (!E
->isTypeDependent() && !E
->getType()->isVectorType())
7785 isVectorLiteral
= true;
7788 isVectorLiteral
= true;
7791 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7792 // then handle it as such.
7793 if (isVectorLiteral
)
7794 return BuildVectorLiteral(LParenLoc
, RParenLoc
, CastExpr
, castTInfo
);
7796 // If the Expr being casted is a ParenListExpr, handle it specially.
7797 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7798 // sequence of BinOp comma operators.
7799 if (isa
<ParenListExpr
>(CastExpr
)) {
7800 ExprResult Result
= MaybeConvertParenListExprToParenExpr(S
, CastExpr
);
7801 if (Result
.isInvalid()) return ExprError();
7802 CastExpr
= Result
.get();
7805 if (getLangOpts().CPlusPlus
&& !castType
->isVoidType())
7806 Diag(LParenLoc
, diag::warn_old_style_cast
) << CastExpr
->getSourceRange();
7808 ObjC().CheckTollFreeBridgeCast(castType
, CastExpr
);
7810 ObjC().CheckObjCBridgeRelatedCast(castType
, CastExpr
);
7812 DiscardMisalignedMemberAddress(castType
.getTypePtr(), CastExpr
);
7814 return BuildCStyleCastExpr(LParenLoc
, castTInfo
, RParenLoc
, CastExpr
);
7817 ExprResult
Sema::BuildVectorLiteral(SourceLocation LParenLoc
,
7818 SourceLocation RParenLoc
, Expr
*E
,
7819 TypeSourceInfo
*TInfo
) {
7820 assert((isa
<ParenListExpr
>(E
) || isa
<ParenExpr
>(E
)) &&
7821 "Expected paren or paren list expression");
7826 SourceLocation LiteralLParenLoc
, LiteralRParenLoc
;
7827 if (ParenListExpr
*PE
= dyn_cast
<ParenListExpr
>(E
)) {
7828 LiteralLParenLoc
= PE
->getLParenLoc();
7829 LiteralRParenLoc
= PE
->getRParenLoc();
7830 exprs
= PE
->getExprs();
7831 numExprs
= PE
->getNumExprs();
7832 } else { // isa<ParenExpr> by assertion at function entrance
7833 LiteralLParenLoc
= cast
<ParenExpr
>(E
)->getLParen();
7834 LiteralRParenLoc
= cast
<ParenExpr
>(E
)->getRParen();
7835 subExpr
= cast
<ParenExpr
>(E
)->getSubExpr();
7840 QualType Ty
= TInfo
->getType();
7841 assert(Ty
->isVectorType() && "Expected vector type");
7843 SmallVector
<Expr
*, 8> initExprs
;
7844 const VectorType
*VTy
= Ty
->castAs
<VectorType
>();
7845 unsigned numElems
= VTy
->getNumElements();
7847 // '(...)' form of vector initialization in AltiVec: the number of
7848 // initializers must be one or must match the size of the vector.
7849 // If a single value is specified in the initializer then it will be
7850 // replicated to all the components of the vector
7851 if (CheckAltivecInitFromScalar(E
->getSourceRange(), Ty
,
7852 VTy
->getElementType()))
7854 if (ShouldSplatAltivecScalarInCast(VTy
)) {
7855 // The number of initializers must be one or must match the size of the
7856 // vector. If a single value is specified in the initializer then it will
7857 // be replicated to all the components of the vector
7858 if (numExprs
== 1) {
7859 QualType ElemTy
= VTy
->getElementType();
7860 ExprResult Literal
= DefaultLvalueConversion(exprs
[0]);
7861 if (Literal
.isInvalid())
7863 Literal
= ImpCastExprToType(Literal
.get(), ElemTy
,
7864 PrepareScalarCast(Literal
, ElemTy
));
7865 return BuildCStyleCastExpr(LParenLoc
, TInfo
, RParenLoc
, Literal
.get());
7867 else if (numExprs
< numElems
) {
7868 Diag(E
->getExprLoc(),
7869 diag::err_incorrect_number_of_vector_initializers
);
7873 initExprs
.append(exprs
, exprs
+ numExprs
);
7876 // For OpenCL, when the number of initializers is a single value,
7877 // it will be replicated to all components of the vector.
7878 if (getLangOpts().OpenCL
&& VTy
->getVectorKind() == VectorKind::Generic
&&
7880 QualType ElemTy
= VTy
->getElementType();
7881 ExprResult Literal
= DefaultLvalueConversion(exprs
[0]);
7882 if (Literal
.isInvalid())
7884 Literal
= ImpCastExprToType(Literal
.get(), ElemTy
,
7885 PrepareScalarCast(Literal
, ElemTy
));
7886 return BuildCStyleCastExpr(LParenLoc
, TInfo
, RParenLoc
, Literal
.get());
7889 initExprs
.append(exprs
, exprs
+ numExprs
);
7891 // FIXME: This means that pretty-printing the final AST will produce curly
7892 // braces instead of the original commas.
7893 InitListExpr
*initE
= new (Context
) InitListExpr(Context
, LiteralLParenLoc
,
7894 initExprs
, LiteralRParenLoc
);
7896 return BuildCompoundLiteralExpr(LParenLoc
, TInfo
, RParenLoc
, initE
);
7900 Sema::MaybeConvertParenListExprToParenExpr(Scope
*S
, Expr
*OrigExpr
) {
7901 ParenListExpr
*E
= dyn_cast
<ParenListExpr
>(OrigExpr
);
7905 ExprResult
Result(E
->getExpr(0));
7907 for (unsigned i
= 1, e
= E
->getNumExprs(); i
!= e
&& !Result
.isInvalid(); ++i
)
7908 Result
= ActOnBinOp(S
, E
->getExprLoc(), tok::comma
, Result
.get(),
7911 if (Result
.isInvalid()) return ExprError();
7913 return ActOnParenExpr(E
->getLParenLoc(), E
->getRParenLoc(), Result
.get());
7916 ExprResult
Sema::ActOnParenListExpr(SourceLocation L
,
7919 return ParenListExpr::Create(Context
, L
, Val
, R
);
7922 bool Sema::DiagnoseConditionalForNull(const Expr
*LHSExpr
, const Expr
*RHSExpr
,
7923 SourceLocation QuestionLoc
) {
7924 const Expr
*NullExpr
= LHSExpr
;
7925 const Expr
*NonPointerExpr
= RHSExpr
;
7926 Expr::NullPointerConstantKind NullKind
=
7927 NullExpr
->isNullPointerConstant(Context
,
7928 Expr::NPC_ValueDependentIsNotNull
);
7930 if (NullKind
== Expr::NPCK_NotNull
) {
7932 NonPointerExpr
= LHSExpr
;
7934 NullExpr
->isNullPointerConstant(Context
,
7935 Expr::NPC_ValueDependentIsNotNull
);
7938 if (NullKind
== Expr::NPCK_NotNull
)
7941 if (NullKind
== Expr::NPCK_ZeroExpression
)
7944 if (NullKind
== Expr::NPCK_ZeroLiteral
) {
7945 // In this case, check to make sure that we got here from a "NULL"
7946 // string in the source code.
7947 NullExpr
= NullExpr
->IgnoreParenImpCasts();
7948 SourceLocation loc
= NullExpr
->getExprLoc();
7949 if (!findMacroSpelling(loc
, "NULL"))
7953 int DiagType
= (NullKind
== Expr::NPCK_CXX11_nullptr
);
7954 Diag(QuestionLoc
, diag::err_typecheck_cond_incompatible_operands_null
)
7955 << NonPointerExpr
->getType() << DiagType
7956 << NonPointerExpr
->getSourceRange();
7960 /// Return false if the condition expression is valid, true otherwise.
7961 static bool checkCondition(Sema
&S
, const Expr
*Cond
,
7962 SourceLocation QuestionLoc
) {
7963 QualType CondTy
= Cond
->getType();
7965 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7966 if (S
.getLangOpts().OpenCL
&& CondTy
->isFloatingType()) {
7967 S
.Diag(QuestionLoc
, diag::err_typecheck_cond_expect_nonfloat
)
7968 << CondTy
<< Cond
->getSourceRange();
7973 if (CondTy
->isScalarType()) return false;
7975 S
.Diag(QuestionLoc
, diag::err_typecheck_cond_expect_scalar
)
7976 << CondTy
<< Cond
->getSourceRange();
7980 /// Return false if the NullExpr can be promoted to PointerTy,
7982 static bool checkConditionalNullPointer(Sema
&S
, ExprResult
&NullExpr
,
7983 QualType PointerTy
) {
7984 if ((!PointerTy
->isAnyPointerType() && !PointerTy
->isBlockPointerType()) ||
7985 !NullExpr
.get()->isNullPointerConstant(S
.Context
,
7986 Expr::NPC_ValueDependentIsNull
))
7989 NullExpr
= S
.ImpCastExprToType(NullExpr
.get(), PointerTy
, CK_NullToPointer
);
7993 /// Checks compatibility between two pointers and return the resulting
7995 static QualType
checkConditionalPointerCompatibility(Sema
&S
, ExprResult
&LHS
,
7997 SourceLocation Loc
) {
7998 QualType LHSTy
= LHS
.get()->getType();
7999 QualType RHSTy
= RHS
.get()->getType();
8001 if (S
.Context
.hasSameType(LHSTy
, RHSTy
)) {
8002 // Two identical pointers types are always compatible.
8003 return S
.Context
.getCommonSugaredType(LHSTy
, RHSTy
);
8006 QualType lhptee
, rhptee
;
8008 // Get the pointee types.
8009 bool IsBlockPointer
= false;
8010 if (const BlockPointerType
*LHSBTy
= LHSTy
->getAs
<BlockPointerType
>()) {
8011 lhptee
= LHSBTy
->getPointeeType();
8012 rhptee
= RHSTy
->castAs
<BlockPointerType
>()->getPointeeType();
8013 IsBlockPointer
= true;
8015 lhptee
= LHSTy
->castAs
<PointerType
>()->getPointeeType();
8016 rhptee
= RHSTy
->castAs
<PointerType
>()->getPointeeType();
8019 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8020 // differently qualified versions of compatible types, the result type is
8021 // a pointer to an appropriately qualified version of the composite
8024 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8025 // clause doesn't make sense for our extensions. E.g. address space 2 should
8026 // be incompatible with address space 3: they may live on different devices or
8028 Qualifiers lhQual
= lhptee
.getQualifiers();
8029 Qualifiers rhQual
= rhptee
.getQualifiers();
8031 LangAS ResultAddrSpace
= LangAS::Default
;
8032 LangAS LAddrSpace
= lhQual
.getAddressSpace();
8033 LangAS RAddrSpace
= rhQual
.getAddressSpace();
8035 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8036 // spaces is disallowed.
8037 if (lhQual
.isAddressSpaceSupersetOf(rhQual
, S
.getASTContext()))
8038 ResultAddrSpace
= LAddrSpace
;
8039 else if (rhQual
.isAddressSpaceSupersetOf(lhQual
, S
.getASTContext()))
8040 ResultAddrSpace
= RAddrSpace
;
8042 S
.Diag(Loc
, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers
)
8043 << LHSTy
<< RHSTy
<< 2 << LHS
.get()->getSourceRange()
8044 << RHS
.get()->getSourceRange();
8048 unsigned MergedCVRQual
= lhQual
.getCVRQualifiers() | rhQual
.getCVRQualifiers();
8049 auto LHSCastKind
= CK_BitCast
, RHSCastKind
= CK_BitCast
;
8050 lhQual
.removeCVRQualifiers();
8051 rhQual
.removeCVRQualifiers();
8053 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8054 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8055 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8056 // qual types are compatible iff
8057 // * corresponded types are compatible
8058 // * CVR qualifiers are equal
8059 // * address spaces are equal
8060 // Thus for conditional operator we merge CVR and address space unqualified
8061 // pointees and if there is a composite type we return a pointer to it with
8062 // merged qualifiers.
8064 LAddrSpace
== ResultAddrSpace
? CK_BitCast
: CK_AddressSpaceConversion
;
8066 RAddrSpace
== ResultAddrSpace
? CK_BitCast
: CK_AddressSpaceConversion
;
8067 lhQual
.removeAddressSpace();
8068 rhQual
.removeAddressSpace();
8070 lhptee
= S
.Context
.getQualifiedType(lhptee
.getUnqualifiedType(), lhQual
);
8071 rhptee
= S
.Context
.getQualifiedType(rhptee
.getUnqualifiedType(), rhQual
);
8073 QualType CompositeTy
= S
.Context
.mergeTypes(
8074 lhptee
, rhptee
, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8075 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8077 if (CompositeTy
.isNull()) {
8078 // In this situation, we assume void* type. No especially good
8079 // reason, but this is what gcc does, and we do have to pick
8080 // to get a consistent AST.
8081 QualType incompatTy
;
8082 incompatTy
= S
.Context
.getPointerType(
8083 S
.Context
.getAddrSpaceQualType(S
.Context
.VoidTy
, ResultAddrSpace
));
8084 LHS
= S
.ImpCastExprToType(LHS
.get(), incompatTy
, LHSCastKind
);
8085 RHS
= S
.ImpCastExprToType(RHS
.get(), incompatTy
, RHSCastKind
);
8087 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8088 // for casts between types with incompatible address space qualifiers.
8089 // For the following code the compiler produces casts between global and
8090 // local address spaces of the corresponded innermost pointees:
8091 // local int *global *a;
8092 // global int *global *b;
8093 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8094 S
.Diag(Loc
, diag::ext_typecheck_cond_incompatible_pointers
)
8095 << LHSTy
<< RHSTy
<< LHS
.get()->getSourceRange()
8096 << RHS
.get()->getSourceRange();
8101 // The pointer types are compatible.
8102 // In case of OpenCL ResultTy should have the address space qualifier
8103 // which is a superset of address spaces of both the 2nd and the 3rd
8104 // operands of the conditional operator.
8105 QualType ResultTy
= [&, ResultAddrSpace
]() {
8106 if (S
.getLangOpts().OpenCL
) {
8107 Qualifiers CompositeQuals
= CompositeTy
.getQualifiers();
8108 CompositeQuals
.setAddressSpace(ResultAddrSpace
);
8110 .getQualifiedType(CompositeTy
.getUnqualifiedType(), CompositeQuals
)
8111 .withCVRQualifiers(MergedCVRQual
);
8113 return CompositeTy
.withCVRQualifiers(MergedCVRQual
);
8116 ResultTy
= S
.Context
.getBlockPointerType(ResultTy
);
8118 ResultTy
= S
.Context
.getPointerType(ResultTy
);
8120 LHS
= S
.ImpCastExprToType(LHS
.get(), ResultTy
, LHSCastKind
);
8121 RHS
= S
.ImpCastExprToType(RHS
.get(), ResultTy
, RHSCastKind
);
8125 /// Return the resulting type when the operands are both block pointers.
8126 static QualType
checkConditionalBlockPointerCompatibility(Sema
&S
,
8129 SourceLocation Loc
) {
8130 QualType LHSTy
= LHS
.get()->getType();
8131 QualType RHSTy
= RHS
.get()->getType();
8133 if (!LHSTy
->isBlockPointerType() || !RHSTy
->isBlockPointerType()) {
8134 if (LHSTy
->isVoidPointerType() || RHSTy
->isVoidPointerType()) {
8135 QualType destType
= S
.Context
.getPointerType(S
.Context
.VoidTy
);
8136 LHS
= S
.ImpCastExprToType(LHS
.get(), destType
, CK_BitCast
);
8137 RHS
= S
.ImpCastExprToType(RHS
.get(), destType
, CK_BitCast
);
8140 S
.Diag(Loc
, diag::err_typecheck_cond_incompatible_operands
)
8141 << LHSTy
<< RHSTy
<< LHS
.get()->getSourceRange()
8142 << RHS
.get()->getSourceRange();
8146 // We have 2 block pointer types.
8147 return checkConditionalPointerCompatibility(S
, LHS
, RHS
, Loc
);
8150 /// Return the resulting type when the operands are both pointers.
8152 checkConditionalObjectPointersCompatibility(Sema
&S
, ExprResult
&LHS
,
8154 SourceLocation Loc
) {
8155 // get the pointer types
8156 QualType LHSTy
= LHS
.get()->getType();
8157 QualType RHSTy
= RHS
.get()->getType();
8159 // get the "pointed to" types
8160 QualType lhptee
= LHSTy
->castAs
<PointerType
>()->getPointeeType();
8161 QualType rhptee
= RHSTy
->castAs
<PointerType
>()->getPointeeType();
8163 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8164 if (lhptee
->isVoidType() && rhptee
->isIncompleteOrObjectType()) {
8165 // Figure out necessary qualifiers (C99 6.5.15p6)
8166 QualType destPointee
8167 = S
.Context
.getQualifiedType(lhptee
, rhptee
.getQualifiers());
8168 QualType destType
= S
.Context
.getPointerType(destPointee
);
8169 // Add qualifiers if necessary.
8170 LHS
= S
.ImpCastExprToType(LHS
.get(), destType
, CK_NoOp
);
8171 // Promote to void*.
8172 RHS
= S
.ImpCastExprToType(RHS
.get(), destType
, CK_BitCast
);
8175 if (rhptee
->isVoidType() && lhptee
->isIncompleteOrObjectType()) {
8176 QualType destPointee
8177 = S
.Context
.getQualifiedType(rhptee
, lhptee
.getQualifiers());
8178 QualType destType
= S
.Context
.getPointerType(destPointee
);
8179 // Add qualifiers if necessary.
8180 RHS
= S
.ImpCastExprToType(RHS
.get(), destType
, CK_NoOp
);
8181 // Promote to void*.
8182 LHS
= S
.ImpCastExprToType(LHS
.get(), destType
, CK_BitCast
);
8186 return checkConditionalPointerCompatibility(S
, LHS
, RHS
, Loc
);
8189 /// Return false if the first expression is not an integer and the second
8190 /// expression is not a pointer, true otherwise.
8191 static bool checkPointerIntegerMismatch(Sema
&S
, ExprResult
&Int
,
8192 Expr
* PointerExpr
, SourceLocation Loc
,
8193 bool IsIntFirstExpr
) {
8194 if (!PointerExpr
->getType()->isPointerType() ||
8195 !Int
.get()->getType()->isIntegerType())
8198 Expr
*Expr1
= IsIntFirstExpr
? Int
.get() : PointerExpr
;
8199 Expr
*Expr2
= IsIntFirstExpr
? PointerExpr
: Int
.get();
8201 S
.Diag(Loc
, diag::ext_typecheck_cond_pointer_integer_mismatch
)
8202 << Expr1
->getType() << Expr2
->getType()
8203 << Expr1
->getSourceRange() << Expr2
->getSourceRange();
8204 Int
= S
.ImpCastExprToType(Int
.get(), PointerExpr
->getType(),
8205 CK_IntegralToPointer
);
8209 /// Simple conversion between integer and floating point types.
8211 /// Used when handling the OpenCL conditional operator where the
8212 /// condition is a vector while the other operands are scalar.
8214 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8215 /// types are either integer or floating type. Between the two
8216 /// operands, the type with the higher rank is defined as the "result
8217 /// type". The other operand needs to be promoted to the same type. No
8218 /// other type promotion is allowed. We cannot use
8219 /// UsualArithmeticConversions() for this purpose, since it always
8220 /// promotes promotable types.
8221 static QualType
OpenCLArithmeticConversions(Sema
&S
, ExprResult
&LHS
,
8223 SourceLocation QuestionLoc
) {
8224 LHS
= S
.DefaultFunctionArrayLvalueConversion(LHS
.get());
8225 if (LHS
.isInvalid())
8227 RHS
= S
.DefaultFunctionArrayLvalueConversion(RHS
.get());
8228 if (RHS
.isInvalid())
8231 // For conversion purposes, we ignore any qualifiers.
8232 // For example, "const float" and "float" are equivalent.
8234 S
.Context
.getCanonicalType(LHS
.get()->getType()).getUnqualifiedType();
8236 S
.Context
.getCanonicalType(RHS
.get()->getType()).getUnqualifiedType();
8238 if (!LHSType
->isIntegerType() && !LHSType
->isRealFloatingType()) {
8239 S
.Diag(QuestionLoc
, diag::err_typecheck_cond_expect_int_float
)
8240 << LHSType
<< LHS
.get()->getSourceRange();
8244 if (!RHSType
->isIntegerType() && !RHSType
->isRealFloatingType()) {
8245 S
.Diag(QuestionLoc
, diag::err_typecheck_cond_expect_int_float
)
8246 << RHSType
<< RHS
.get()->getSourceRange();
8250 // If both types are identical, no conversion is needed.
8251 if (LHSType
== RHSType
)
8254 // Now handle "real" floating types (i.e. float, double, long double).
8255 if (LHSType
->isRealFloatingType() || RHSType
->isRealFloatingType())
8256 return handleFloatConversion(S
, LHS
, RHS
, LHSType
, RHSType
,
8257 /*IsCompAssign = */ false);
8259 // Finally, we have two differing integer types.
8260 return handleIntegerConversion
<doIntegralCast
, doIntegralCast
>
8261 (S
, LHS
, RHS
, LHSType
, RHSType
, /*IsCompAssign = */ false);
8264 /// Convert scalar operands to a vector that matches the
8265 /// condition in length.
8267 /// Used when handling the OpenCL conditional operator where the
8268 /// condition is a vector while the other operands are scalar.
8270 /// We first compute the "result type" for the scalar operands
8271 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8272 /// into a vector of that type where the length matches the condition
8273 /// vector type. s6.11.6 requires that the element types of the result
8274 /// and the condition must have the same number of bits.
8276 OpenCLConvertScalarsToVectors(Sema
&S
, ExprResult
&LHS
, ExprResult
&RHS
,
8277 QualType CondTy
, SourceLocation QuestionLoc
) {
8278 QualType ResTy
= OpenCLArithmeticConversions(S
, LHS
, RHS
, QuestionLoc
);
8279 if (ResTy
.isNull()) return QualType();
8281 const VectorType
*CV
= CondTy
->getAs
<VectorType
>();
8284 // Determine the vector result type
8285 unsigned NumElements
= CV
->getNumElements();
8286 QualType VectorTy
= S
.Context
.getExtVectorType(ResTy
, NumElements
);
8288 // Ensure that all types have the same number of bits
8289 if (S
.Context
.getTypeSize(CV
->getElementType())
8290 != S
.Context
.getTypeSize(ResTy
)) {
8291 // Since VectorTy is created internally, it does not pretty print
8292 // with an OpenCL name. Instead, we just print a description.
8293 std::string EleTyName
= ResTy
.getUnqualifiedType().getAsString();
8294 SmallString
<64> Str
;
8295 llvm::raw_svector_ostream
OS(Str
);
8296 OS
<< "(vector of " << NumElements
<< " '" << EleTyName
<< "' values)";
8297 S
.Diag(QuestionLoc
, diag::err_conditional_vector_element_size
)
8298 << CondTy
<< OS
.str();
8302 // Convert operands to the vector result type
8303 LHS
= S
.ImpCastExprToType(LHS
.get(), VectorTy
, CK_VectorSplat
);
8304 RHS
= S
.ImpCastExprToType(RHS
.get(), VectorTy
, CK_VectorSplat
);
8309 /// Return false if this is a valid OpenCL condition vector
8310 static bool checkOpenCLConditionVector(Sema
&S
, Expr
*Cond
,
8311 SourceLocation QuestionLoc
) {
8312 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8314 const VectorType
*CondTy
= Cond
->getType()->getAs
<VectorType
>();
8316 QualType EleTy
= CondTy
->getElementType();
8317 if (EleTy
->isIntegerType()) return false;
8319 S
.Diag(QuestionLoc
, diag::err_typecheck_cond_expect_nonfloat
)
8320 << Cond
->getType() << Cond
->getSourceRange();
8324 /// Return false if the vector condition type and the vector
8325 /// result type are compatible.
8327 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8328 /// number of elements, and their element types have the same number
8330 static bool checkVectorResult(Sema
&S
, QualType CondTy
, QualType VecResTy
,
8331 SourceLocation QuestionLoc
) {
8332 const VectorType
*CV
= CondTy
->getAs
<VectorType
>();
8333 const VectorType
*RV
= VecResTy
->getAs
<VectorType
>();
8336 if (CV
->getNumElements() != RV
->getNumElements()) {
8337 S
.Diag(QuestionLoc
, diag::err_conditional_vector_size
)
8338 << CondTy
<< VecResTy
;
8342 QualType CVE
= CV
->getElementType();
8343 QualType RVE
= RV
->getElementType();
8345 if (S
.Context
.getTypeSize(CVE
) != S
.Context
.getTypeSize(RVE
)) {
8346 S
.Diag(QuestionLoc
, diag::err_conditional_vector_element_size
)
8347 << CondTy
<< VecResTy
;
8354 /// Return the resulting type for the conditional operator in
8355 /// OpenCL (aka "ternary selection operator", OpenCL v1.1
8356 /// s6.3.i) when the condition is a vector type.
8358 OpenCLCheckVectorConditional(Sema
&S
, ExprResult
&Cond
,
8359 ExprResult
&LHS
, ExprResult
&RHS
,
8360 SourceLocation QuestionLoc
) {
8361 Cond
= S
.DefaultFunctionArrayLvalueConversion(Cond
.get());
8362 if (Cond
.isInvalid())
8364 QualType CondTy
= Cond
.get()->getType();
8366 if (checkOpenCLConditionVector(S
, Cond
.get(), QuestionLoc
))
8369 // If either operand is a vector then find the vector type of the
8370 // result as specified in OpenCL v1.1 s6.3.i.
8371 if (LHS
.get()->getType()->isVectorType() ||
8372 RHS
.get()->getType()->isVectorType()) {
8373 bool IsBoolVecLang
=
8374 !S
.getLangOpts().OpenCL
&& !S
.getLangOpts().OpenCLCPlusPlus
;
8376 S
.CheckVectorOperands(LHS
, RHS
, QuestionLoc
,
8377 /*isCompAssign*/ false,
8378 /*AllowBothBool*/ true,
8379 /*AllowBoolConversions*/ false,
8380 /*AllowBooleanOperation*/ IsBoolVecLang
,
8381 /*ReportInvalid*/ true);
8382 if (VecResTy
.isNull())
8384 // The result type must match the condition type as specified in
8385 // OpenCL v1.1 s6.11.6.
8386 if (checkVectorResult(S
, CondTy
, VecResTy
, QuestionLoc
))
8391 // Both operands are scalar.
8392 return OpenCLConvertScalarsToVectors(S
, LHS
, RHS
, CondTy
, QuestionLoc
);
8395 /// Return true if the Expr is block type
8396 static bool checkBlockType(Sema
&S
, const Expr
*E
) {
8397 if (const CallExpr
*CE
= dyn_cast
<CallExpr
>(E
)) {
8398 QualType Ty
= CE
->getCallee()->getType();
8399 if (Ty
->isBlockPointerType()) {
8400 S
.Diag(E
->getExprLoc(), diag::err_opencl_ternary_with_block
);
8407 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8408 /// In that case, LHS = cond.
8410 QualType
Sema::CheckConditionalOperands(ExprResult
&Cond
, ExprResult
&LHS
,
8411 ExprResult
&RHS
, ExprValueKind
&VK
,
8413 SourceLocation QuestionLoc
) {
8415 ExprResult LHSResult
= CheckPlaceholderExpr(LHS
.get());
8416 if (!LHSResult
.isUsable()) return QualType();
8419 ExprResult RHSResult
= CheckPlaceholderExpr(RHS
.get());
8420 if (!RHSResult
.isUsable()) return QualType();
8423 // C++ is sufficiently different to merit its own checker.
8424 if (getLangOpts().CPlusPlus
)
8425 return CXXCheckConditionalOperands(Cond
, LHS
, RHS
, VK
, OK
, QuestionLoc
);
8430 if (Context
.isDependenceAllowed() &&
8431 (Cond
.get()->isTypeDependent() || LHS
.get()->isTypeDependent() ||
8432 RHS
.get()->isTypeDependent())) {
8433 assert(!getLangOpts().CPlusPlus
);
8434 assert((Cond
.get()->containsErrors() || LHS
.get()->containsErrors() ||
8435 RHS
.get()->containsErrors()) &&
8436 "should only occur in error-recovery path.");
8437 return Context
.DependentTy
;
8440 // The OpenCL operator with a vector condition is sufficiently
8441 // different to merit its own checker.
8442 if ((getLangOpts().OpenCL
&& Cond
.get()->getType()->isVectorType()) ||
8443 Cond
.get()->getType()->isExtVectorType())
8444 return OpenCLCheckVectorConditional(*this, Cond
, LHS
, RHS
, QuestionLoc
);
8446 // First, check the condition.
8447 Cond
= UsualUnaryConversions(Cond
.get());
8448 if (Cond
.isInvalid())
8450 if (checkCondition(*this, Cond
.get(), QuestionLoc
))
8454 if (LHS
.get()->getType()->isVectorType() ||
8455 RHS
.get()->getType()->isVectorType())
8456 return CheckVectorOperands(LHS
, RHS
, QuestionLoc
, /*isCompAssign*/ false,
8457 /*AllowBothBool*/ true,
8458 /*AllowBoolConversions*/ false,
8459 /*AllowBooleanOperation*/ false,
8460 /*ReportInvalid*/ true);
8463 UsualArithmeticConversions(LHS
, RHS
, QuestionLoc
, ACK_Conditional
);
8464 if (LHS
.isInvalid() || RHS
.isInvalid())
8467 // WebAssembly tables are not allowed as conditional LHS or RHS.
8468 QualType LHSTy
= LHS
.get()->getType();
8469 QualType RHSTy
= RHS
.get()->getType();
8470 if (LHSTy
->isWebAssemblyTableType() || RHSTy
->isWebAssemblyTableType()) {
8471 Diag(QuestionLoc
, diag::err_wasm_table_conditional_expression
)
8472 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
8476 // Diagnose attempts to convert between __ibm128, __float128 and long double
8477 // where such conversions currently can't be handled.
8478 if (unsupportedTypeConversion(*this, LHSTy
, RHSTy
)) {
8480 diag::err_typecheck_cond_incompatible_operands
) << LHSTy
<< RHSTy
8481 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
8485 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8486 // selection operator (?:).
8487 if (getLangOpts().OpenCL
&&
8488 ((int)checkBlockType(*this, LHS
.get()) | (int)checkBlockType(*this, RHS
.get()))) {
8492 // If both operands have arithmetic type, do the usual arithmetic conversions
8493 // to find a common type: C99 6.5.15p3,5.
8494 if (LHSTy
->isArithmeticType() && RHSTy
->isArithmeticType()) {
8495 // Disallow invalid arithmetic conversions, such as those between bit-
8496 // precise integers types of different sizes, or between a bit-precise
8497 // integer and another type.
8498 if (ResTy
.isNull() && (LHSTy
->isBitIntType() || RHSTy
->isBitIntType())) {
8499 Diag(QuestionLoc
, diag::err_typecheck_cond_incompatible_operands
)
8500 << LHSTy
<< RHSTy
<< LHS
.get()->getSourceRange()
8501 << RHS
.get()->getSourceRange();
8505 LHS
= ImpCastExprToType(LHS
.get(), ResTy
, PrepareScalarCast(LHS
, ResTy
));
8506 RHS
= ImpCastExprToType(RHS
.get(), ResTy
, PrepareScalarCast(RHS
, ResTy
));
8511 // If both operands are the same structure or union type, the result is that
8513 if (const RecordType
*LHSRT
= LHSTy
->getAs
<RecordType
>()) { // C99 6.5.15p3
8514 if (const RecordType
*RHSRT
= RHSTy
->getAs
<RecordType
>())
8515 if (LHSRT
->getDecl() == RHSRT
->getDecl())
8516 // "If both the operands have structure or union type, the result has
8517 // that type." This implies that CV qualifiers are dropped.
8518 return Context
.getCommonSugaredType(LHSTy
.getUnqualifiedType(),
8519 RHSTy
.getUnqualifiedType());
8520 // FIXME: Type of conditional expression must be complete in C mode.
8523 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8524 // The following || allows only one side to be void (a GCC-ism).
8525 if (LHSTy
->isVoidType() || RHSTy
->isVoidType()) {
8527 if (LHSTy
->isVoidType() && RHSTy
->isVoidType()) {
8528 ResTy
= Context
.getCommonSugaredType(LHSTy
, RHSTy
);
8529 } else if (RHSTy
->isVoidType()) {
8531 Diag(RHS
.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void
)
8532 << RHS
.get()->getSourceRange();
8535 Diag(LHS
.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void
)
8536 << LHS
.get()->getSourceRange();
8538 LHS
= ImpCastExprToType(LHS
.get(), ResTy
, CK_ToVoid
);
8539 RHS
= ImpCastExprToType(RHS
.get(), ResTy
, CK_ToVoid
);
8544 // ... if both the second and third operands have nullptr_t type, the
8545 // result also has that type.
8546 if (LHSTy
->isNullPtrType() && Context
.hasSameType(LHSTy
, RHSTy
))
8549 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8550 // the type of the other operand."
8551 if (!checkConditionalNullPointer(*this, RHS
, LHSTy
)) return LHSTy
;
8552 if (!checkConditionalNullPointer(*this, LHS
, RHSTy
)) return RHSTy
;
8554 // All objective-c pointer type analysis is done here.
8555 QualType compositeType
=
8556 ObjC().FindCompositeObjCPointerType(LHS
, RHS
, QuestionLoc
);
8557 if (LHS
.isInvalid() || RHS
.isInvalid())
8559 if (!compositeType
.isNull())
8560 return compositeType
;
8563 // Handle block pointer types.
8564 if (LHSTy
->isBlockPointerType() || RHSTy
->isBlockPointerType())
8565 return checkConditionalBlockPointerCompatibility(*this, LHS
, RHS
,
8568 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8569 if (LHSTy
->isPointerType() && RHSTy
->isPointerType())
8570 return checkConditionalObjectPointersCompatibility(*this, LHS
, RHS
,
8573 // GCC compatibility: soften pointer/integer mismatch. Note that
8574 // null pointers have been filtered out by this point.
8575 if (checkPointerIntegerMismatch(*this, LHS
, RHS
.get(), QuestionLoc
,
8576 /*IsIntFirstExpr=*/true))
8578 if (checkPointerIntegerMismatch(*this, RHS
, LHS
.get(), QuestionLoc
,
8579 /*IsIntFirstExpr=*/false))
8582 // Emit a better diagnostic if one of the expressions is a null pointer
8583 // constant and the other is not a pointer type. In this case, the user most
8584 // likely forgot to take the address of the other expression.
8585 if (DiagnoseConditionalForNull(LHS
.get(), RHS
.get(), QuestionLoc
))
8588 // Finally, if the LHS and RHS types are canonically the same type, we can
8589 // use the common sugared type.
8590 if (Context
.hasSameType(LHSTy
, RHSTy
))
8591 return Context
.getCommonSugaredType(LHSTy
, RHSTy
);
8593 // Otherwise, the operands are not compatible.
8594 Diag(QuestionLoc
, diag::err_typecheck_cond_incompatible_operands
)
8595 << LHSTy
<< RHSTy
<< LHS
.get()->getSourceRange()
8596 << RHS
.get()->getSourceRange();
8600 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8601 /// ParenRange in parentheses.
8602 static void SuggestParentheses(Sema
&Self
, SourceLocation Loc
,
8603 const PartialDiagnostic
&Note
,
8604 SourceRange ParenRange
) {
8605 SourceLocation EndLoc
= Self
.getLocForEndOfToken(ParenRange
.getEnd());
8606 if (ParenRange
.getBegin().isFileID() && ParenRange
.getEnd().isFileID() &&
8608 Self
.Diag(Loc
, Note
)
8609 << FixItHint::CreateInsertion(ParenRange
.getBegin(), "(")
8610 << FixItHint::CreateInsertion(EndLoc
, ")");
8612 // We can't display the parentheses, so just show the bare note.
8613 Self
.Diag(Loc
, Note
) << ParenRange
;
8617 static bool IsArithmeticOp(BinaryOperatorKind Opc
) {
8618 return BinaryOperator::isAdditiveOp(Opc
) ||
8619 BinaryOperator::isMultiplicativeOp(Opc
) ||
8620 BinaryOperator::isShiftOp(Opc
) || Opc
== BO_And
|| Opc
== BO_Or
;
8621 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8622 // not any of the logical operators. Bitwise-xor is commonly used as a
8623 // logical-xor because there is no logical-xor operator. The logical
8624 // operators, including uses of xor, have a high false positive rate for
8625 // precedence warnings.
8628 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8629 /// expression, either using a built-in or overloaded operator,
8630 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8632 static bool IsArithmeticBinaryExpr(const Expr
*E
, BinaryOperatorKind
*Opcode
,
8633 const Expr
**RHSExprs
) {
8634 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8635 E
= E
->IgnoreImpCasts();
8636 E
= E
->IgnoreConversionOperatorSingleStep();
8637 E
= E
->IgnoreImpCasts();
8638 if (const auto *MTE
= dyn_cast
<MaterializeTemporaryExpr
>(E
)) {
8639 E
= MTE
->getSubExpr();
8640 E
= E
->IgnoreImpCasts();
8643 // Built-in binary operator.
8644 if (const auto *OP
= dyn_cast
<BinaryOperator
>(E
);
8645 OP
&& IsArithmeticOp(OP
->getOpcode())) {
8646 *Opcode
= OP
->getOpcode();
8647 *RHSExprs
= OP
->getRHS();
8651 // Overloaded operator.
8652 if (const auto *Call
= dyn_cast
<CXXOperatorCallExpr
>(E
)) {
8653 if (Call
->getNumArgs() != 2)
8656 // Make sure this is really a binary operator that is safe to pass into
8657 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8658 OverloadedOperatorKind OO
= Call
->getOperator();
8659 if (OO
< OO_Plus
|| OO
> OO_Arrow
||
8660 OO
== OO_PlusPlus
|| OO
== OO_MinusMinus
)
8663 BinaryOperatorKind OpKind
= BinaryOperator::getOverloadedOpcode(OO
);
8664 if (IsArithmeticOp(OpKind
)) {
8666 *RHSExprs
= Call
->getArg(1);
8674 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8675 /// or is a logical expression such as (x==y) which has int type, but is
8676 /// commonly interpreted as boolean.
8677 static bool ExprLooksBoolean(const Expr
*E
) {
8678 E
= E
->IgnoreParenImpCasts();
8680 if (E
->getType()->isBooleanType())
8682 if (const auto *OP
= dyn_cast
<BinaryOperator
>(E
))
8683 return OP
->isComparisonOp() || OP
->isLogicalOp();
8684 if (const auto *OP
= dyn_cast
<UnaryOperator
>(E
))
8685 return OP
->getOpcode() == UO_LNot
;
8686 if (E
->getType()->isPointerType())
8688 // FIXME: What about overloaded operator calls returning "unspecified boolean
8689 // type"s (commonly pointer-to-members)?
8694 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8695 /// and binary operator are mixed in a way that suggests the programmer assumed
8696 /// the conditional operator has higher precedence, for example:
8697 /// "int x = a + someBinaryCondition ? 1 : 2".
8698 static void DiagnoseConditionalPrecedence(Sema
&Self
, SourceLocation OpLoc
,
8699 Expr
*Condition
, const Expr
*LHSExpr
,
8700 const Expr
*RHSExpr
) {
8701 BinaryOperatorKind CondOpcode
;
8702 const Expr
*CondRHS
;
8704 if (!IsArithmeticBinaryExpr(Condition
, &CondOpcode
, &CondRHS
))
8706 if (!ExprLooksBoolean(CondRHS
))
8709 // The condition is an arithmetic binary expression, with a right-
8710 // hand side that looks boolean, so warn.
8712 unsigned DiagID
= BinaryOperator::isBitwiseOp(CondOpcode
)
8713 ? diag::warn_precedence_bitwise_conditional
8714 : diag::warn_precedence_conditional
;
8716 Self
.Diag(OpLoc
, DiagID
)
8717 << Condition
->getSourceRange()
8718 << BinaryOperator::getOpcodeStr(CondOpcode
);
8722 Self
.PDiag(diag::note_precedence_silence
)
8723 << BinaryOperator::getOpcodeStr(CondOpcode
),
8724 SourceRange(Condition
->getBeginLoc(), Condition
->getEndLoc()));
8726 SuggestParentheses(Self
, OpLoc
,
8727 Self
.PDiag(diag::note_precedence_conditional_first
),
8728 SourceRange(CondRHS
->getBeginLoc(), RHSExpr
->getEndLoc()));
8731 /// Compute the nullability of a conditional expression.
8732 static QualType
computeConditionalNullability(QualType ResTy
, bool IsBin
,
8733 QualType LHSTy
, QualType RHSTy
,
8735 if (!ResTy
->isAnyPointerType())
8738 auto GetNullability
= [](QualType Ty
) {
8739 std::optional
<NullabilityKind
> Kind
= Ty
->getNullability();
8741 // For our purposes, treat _Nullable_result as _Nullable.
8742 if (*Kind
== NullabilityKind::NullableResult
)
8743 return NullabilityKind::Nullable
;
8746 return NullabilityKind::Unspecified
;
8749 auto LHSKind
= GetNullability(LHSTy
), RHSKind
= GetNullability(RHSTy
);
8750 NullabilityKind MergedKind
;
8752 // Compute nullability of a binary conditional expression.
8754 if (LHSKind
== NullabilityKind::NonNull
)
8755 MergedKind
= NullabilityKind::NonNull
;
8757 MergedKind
= RHSKind
;
8758 // Compute nullability of a normal conditional expression.
8760 if (LHSKind
== NullabilityKind::Nullable
||
8761 RHSKind
== NullabilityKind::Nullable
)
8762 MergedKind
= NullabilityKind::Nullable
;
8763 else if (LHSKind
== NullabilityKind::NonNull
)
8764 MergedKind
= RHSKind
;
8765 else if (RHSKind
== NullabilityKind::NonNull
)
8766 MergedKind
= LHSKind
;
8768 MergedKind
= NullabilityKind::Unspecified
;
8771 // Return if ResTy already has the correct nullability.
8772 if (GetNullability(ResTy
) == MergedKind
)
8775 // Strip all nullability from ResTy.
8776 while (ResTy
->getNullability())
8777 ResTy
= ResTy
.getSingleStepDesugaredType(Ctx
);
8779 // Create a new AttributedType with the new nullability kind.
8780 return Ctx
.getAttributedType(MergedKind
, ResTy
, ResTy
);
8783 ExprResult
Sema::ActOnConditionalOp(SourceLocation QuestionLoc
,
8784 SourceLocation ColonLoc
,
8785 Expr
*CondExpr
, Expr
*LHSExpr
,
8787 if (!Context
.isDependenceAllowed()) {
8788 // C cannot handle TypoExpr nodes in the condition because it
8789 // doesn't handle dependent types properly, so make sure any TypoExprs have
8790 // been dealt with before checking the operands.
8791 ExprResult CondResult
= CorrectDelayedTyposInExpr(CondExpr
);
8792 ExprResult LHSResult
= CorrectDelayedTyposInExpr(LHSExpr
);
8793 ExprResult RHSResult
= CorrectDelayedTyposInExpr(RHSExpr
);
8795 if (!CondResult
.isUsable())
8799 if (!LHSResult
.isUsable())
8803 if (!RHSResult
.isUsable())
8806 CondExpr
= CondResult
.get();
8807 LHSExpr
= LHSResult
.get();
8808 RHSExpr
= RHSResult
.get();
8811 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8812 // was the condition.
8813 OpaqueValueExpr
*opaqueValue
= nullptr;
8814 Expr
*commonExpr
= nullptr;
8816 commonExpr
= CondExpr
;
8817 // Lower out placeholder types first. This is important so that we don't
8818 // try to capture a placeholder. This happens in few cases in C++; such
8819 // as Objective-C++'s dictionary subscripting syntax.
8820 if (commonExpr
->hasPlaceholderType()) {
8821 ExprResult result
= CheckPlaceholderExpr(commonExpr
);
8822 if (!result
.isUsable()) return ExprError();
8823 commonExpr
= result
.get();
8825 // We usually want to apply unary conversions *before* saving, except
8826 // in the special case of a C++ l-value conditional.
8827 if (!(getLangOpts().CPlusPlus
8828 && !commonExpr
->isTypeDependent()
8829 && commonExpr
->getValueKind() == RHSExpr
->getValueKind()
8830 && commonExpr
->isGLValue()
8831 && commonExpr
->isOrdinaryOrBitFieldObject()
8832 && RHSExpr
->isOrdinaryOrBitFieldObject()
8833 && Context
.hasSameType(commonExpr
->getType(), RHSExpr
->getType()))) {
8834 ExprResult commonRes
= UsualUnaryConversions(commonExpr
);
8835 if (commonRes
.isInvalid())
8837 commonExpr
= commonRes
.get();
8840 // If the common expression is a class or array prvalue, materialize it
8841 // so that we can safely refer to it multiple times.
8842 if (commonExpr
->isPRValue() && (commonExpr
->getType()->isRecordType() ||
8843 commonExpr
->getType()->isArrayType())) {
8844 ExprResult MatExpr
= TemporaryMaterializationConversion(commonExpr
);
8845 if (MatExpr
.isInvalid())
8847 commonExpr
= MatExpr
.get();
8850 opaqueValue
= new (Context
) OpaqueValueExpr(commonExpr
->getExprLoc(),
8851 commonExpr
->getType(),
8852 commonExpr
->getValueKind(),
8853 commonExpr
->getObjectKind(),
8855 LHSExpr
= CondExpr
= opaqueValue
;
8858 QualType LHSTy
= LHSExpr
->getType(), RHSTy
= RHSExpr
->getType();
8859 ExprValueKind VK
= VK_PRValue
;
8860 ExprObjectKind OK
= OK_Ordinary
;
8861 ExprResult Cond
= CondExpr
, LHS
= LHSExpr
, RHS
= RHSExpr
;
8862 QualType result
= CheckConditionalOperands(Cond
, LHS
, RHS
,
8863 VK
, OK
, QuestionLoc
);
8864 if (result
.isNull() || Cond
.isInvalid() || LHS
.isInvalid() ||
8868 DiagnoseConditionalPrecedence(*this, QuestionLoc
, Cond
.get(), LHS
.get(),
8871 CheckBoolLikeConversion(Cond
.get(), QuestionLoc
);
8873 result
= computeConditionalNullability(result
, commonExpr
, LHSTy
, RHSTy
,
8877 return new (Context
)
8878 ConditionalOperator(Cond
.get(), QuestionLoc
, LHS
.get(), ColonLoc
,
8879 RHS
.get(), result
, VK
, OK
);
8881 return new (Context
) BinaryConditionalOperator(
8882 commonExpr
, opaqueValue
, Cond
.get(), LHS
.get(), RHS
.get(), QuestionLoc
,
8883 ColonLoc
, result
, VK
, OK
);
8886 bool Sema::IsInvalidSMECallConversion(QualType FromType
, QualType ToType
) {
8887 unsigned FromAttributes
= 0, ToAttributes
= 0;
8888 if (const auto *FromFn
=
8889 dyn_cast
<FunctionProtoType
>(Context
.getCanonicalType(FromType
)))
8891 FromFn
->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask
;
8892 if (const auto *ToFn
=
8893 dyn_cast
<FunctionProtoType
>(Context
.getCanonicalType(ToType
)))
8895 ToFn
->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask
;
8897 return FromAttributes
!= ToAttributes
;
8900 // Check if we have a conversion between incompatible cmse function pointer
8901 // types, that is, a conversion between a function pointer with the
8902 // cmse_nonsecure_call attribute and one without.
8903 static bool IsInvalidCmseNSCallConversion(Sema
&S
, QualType FromType
,
8905 if (const auto *ToFn
=
8906 dyn_cast
<FunctionType
>(S
.Context
.getCanonicalType(ToType
))) {
8907 if (const auto *FromFn
=
8908 dyn_cast
<FunctionType
>(S
.Context
.getCanonicalType(FromType
))) {
8909 FunctionType::ExtInfo ToEInfo
= ToFn
->getExtInfo();
8910 FunctionType::ExtInfo FromEInfo
= FromFn
->getExtInfo();
8912 return ToEInfo
.getCmseNSCall() != FromEInfo
.getCmseNSCall();
8918 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8919 // being closely modeled after the C99 spec:-). The odd characteristic of this
8920 // routine is it effectively iqnores the qualifiers on the top level pointee.
8921 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8922 // FIXME: add a couple examples in this comment.
8923 static Sema::AssignConvertType
8924 checkPointerTypesForAssignment(Sema
&S
, QualType LHSType
, QualType RHSType
,
8925 SourceLocation Loc
) {
8926 assert(LHSType
.isCanonical() && "LHS not canonicalized!");
8927 assert(RHSType
.isCanonical() && "RHS not canonicalized!");
8929 // get the "pointed to" type (ignoring qualifiers at the top level)
8930 const Type
*lhptee
, *rhptee
;
8931 Qualifiers lhq
, rhq
;
8932 std::tie(lhptee
, lhq
) =
8933 cast
<PointerType
>(LHSType
)->getPointeeType().split().asPair();
8934 std::tie(rhptee
, rhq
) =
8935 cast
<PointerType
>(RHSType
)->getPointeeType().split().asPair();
8937 Sema::AssignConvertType ConvTy
= Sema::Compatible
;
8939 // C99 6.5.16.1p1: This following citation is common to constraints
8940 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8941 // qualifiers of the type *pointed to* by the right;
8943 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8944 if (lhq
.getObjCLifetime() != rhq
.getObjCLifetime() &&
8945 lhq
.compatiblyIncludesObjCLifetime(rhq
)) {
8946 // Ignore lifetime for further calculation.
8947 lhq
.removeObjCLifetime();
8948 rhq
.removeObjCLifetime();
8951 if (!lhq
.compatiblyIncludes(rhq
, S
.getASTContext())) {
8952 // Treat address-space mismatches as fatal.
8953 if (!lhq
.isAddressSpaceSupersetOf(rhq
, S
.getASTContext()))
8954 return Sema::IncompatiblePointerDiscardsQualifiers
;
8956 // It's okay to add or remove GC or lifetime qualifiers when converting to
8958 else if (lhq
.withoutObjCGCAttr().withoutObjCLifetime().compatiblyIncludes(
8959 rhq
.withoutObjCGCAttr().withoutObjCLifetime(),
8960 S
.getASTContext()) &&
8961 (lhptee
->isVoidType() || rhptee
->isVoidType()))
8964 // Treat lifetime mismatches as fatal.
8965 else if (lhq
.getObjCLifetime() != rhq
.getObjCLifetime())
8966 ConvTy
= Sema::IncompatiblePointerDiscardsQualifiers
;
8968 // For GCC/MS compatibility, other qualifier mismatches are treated
8969 // as still compatible in C.
8970 else ConvTy
= Sema::CompatiblePointerDiscardsQualifiers
;
8973 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8974 // incomplete type and the other is a pointer to a qualified or unqualified
8975 // version of void...
8976 if (lhptee
->isVoidType()) {
8977 if (rhptee
->isIncompleteOrObjectType())
8980 // As an extension, we allow cast to/from void* to function pointer.
8981 assert(rhptee
->isFunctionType());
8982 return Sema::FunctionVoidPointer
;
8985 if (rhptee
->isVoidType()) {
8986 if (lhptee
->isIncompleteOrObjectType())
8989 // As an extension, we allow cast to/from void* to function pointer.
8990 assert(lhptee
->isFunctionType());
8991 return Sema::FunctionVoidPointer
;
8994 if (!S
.Diags
.isIgnored(
8995 diag::warn_typecheck_convert_incompatible_function_pointer_strict
,
8997 RHSType
->isFunctionPointerType() && LHSType
->isFunctionPointerType() &&
8998 !S
.IsFunctionConversion(RHSType
, LHSType
, RHSType
))
8999 return Sema::IncompatibleFunctionPointerStrict
;
9001 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9002 // unqualified versions of compatible types, ...
9003 QualType ltrans
= QualType(lhptee
, 0), rtrans
= QualType(rhptee
, 0);
9004 if (!S
.Context
.typesAreCompatible(ltrans
, rtrans
)) {
9005 // Check if the pointee types are compatible ignoring the sign.
9006 // We explicitly check for char so that we catch "char" vs
9007 // "unsigned char" on systems where "char" is unsigned.
9008 if (lhptee
->isCharType())
9009 ltrans
= S
.Context
.UnsignedCharTy
;
9010 else if (lhptee
->hasSignedIntegerRepresentation())
9011 ltrans
= S
.Context
.getCorrespondingUnsignedType(ltrans
);
9013 if (rhptee
->isCharType())
9014 rtrans
= S
.Context
.UnsignedCharTy
;
9015 else if (rhptee
->hasSignedIntegerRepresentation())
9016 rtrans
= S
.Context
.getCorrespondingUnsignedType(rtrans
);
9018 if (ltrans
== rtrans
) {
9019 // Types are compatible ignoring the sign. Qualifier incompatibility
9020 // takes priority over sign incompatibility because the sign
9021 // warning can be disabled.
9022 if (ConvTy
!= Sema::Compatible
)
9025 return Sema::IncompatiblePointerSign
;
9028 // If we are a multi-level pointer, it's possible that our issue is simply
9029 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9030 // the eventual target type is the same and the pointers have the same
9031 // level of indirection, this must be the issue.
9032 if (isa
<PointerType
>(lhptee
) && isa
<PointerType
>(rhptee
)) {
9034 std::tie(lhptee
, lhq
) =
9035 cast
<PointerType
>(lhptee
)->getPointeeType().split().asPair();
9036 std::tie(rhptee
, rhq
) =
9037 cast
<PointerType
>(rhptee
)->getPointeeType().split().asPair();
9039 // Inconsistent address spaces at this point is invalid, even if the
9040 // address spaces would be compatible.
9041 // FIXME: This doesn't catch address space mismatches for pointers of
9042 // different nesting levels, like:
9043 // __local int *** a;
9045 // It's not clear how to actually determine when such pointers are
9046 // invalidly incompatible.
9047 if (lhq
.getAddressSpace() != rhq
.getAddressSpace())
9048 return Sema::IncompatibleNestedPointerAddressSpaceMismatch
;
9050 } while (isa
<PointerType
>(lhptee
) && isa
<PointerType
>(rhptee
));
9052 if (lhptee
== rhptee
)
9053 return Sema::IncompatibleNestedPointerQualifiers
;
9056 // General pointer incompatibility takes priority over qualifiers.
9057 if (RHSType
->isFunctionPointerType() && LHSType
->isFunctionPointerType())
9058 return Sema::IncompatibleFunctionPointer
;
9059 return Sema::IncompatiblePointer
;
9061 if (!S
.getLangOpts().CPlusPlus
&&
9062 S
.IsFunctionConversion(ltrans
, rtrans
, ltrans
))
9063 return Sema::IncompatibleFunctionPointer
;
9064 if (IsInvalidCmseNSCallConversion(S
, ltrans
, rtrans
))
9065 return Sema::IncompatibleFunctionPointer
;
9066 if (S
.IsInvalidSMECallConversion(rtrans
, ltrans
))
9067 return Sema::IncompatibleFunctionPointer
;
9071 /// checkBlockPointerTypesForAssignment - This routine determines whether two
9072 /// block pointer types are compatible or whether a block and normal pointer
9073 /// are compatible. It is more restrict than comparing two function pointer
9075 static Sema::AssignConvertType
9076 checkBlockPointerTypesForAssignment(Sema
&S
, QualType LHSType
,
9078 assert(LHSType
.isCanonical() && "LHS not canonicalized!");
9079 assert(RHSType
.isCanonical() && "RHS not canonicalized!");
9081 QualType lhptee
, rhptee
;
9083 // get the "pointed to" type (ignoring qualifiers at the top level)
9084 lhptee
= cast
<BlockPointerType
>(LHSType
)->getPointeeType();
9085 rhptee
= cast
<BlockPointerType
>(RHSType
)->getPointeeType();
9087 // In C++, the types have to match exactly.
9088 if (S
.getLangOpts().CPlusPlus
)
9089 return Sema::IncompatibleBlockPointer
;
9091 Sema::AssignConvertType ConvTy
= Sema::Compatible
;
9093 // For blocks we enforce that qualifiers are identical.
9094 Qualifiers LQuals
= lhptee
.getLocalQualifiers();
9095 Qualifiers RQuals
= rhptee
.getLocalQualifiers();
9096 if (S
.getLangOpts().OpenCL
) {
9097 LQuals
.removeAddressSpace();
9098 RQuals
.removeAddressSpace();
9100 if (LQuals
!= RQuals
)
9101 ConvTy
= Sema::CompatiblePointerDiscardsQualifiers
;
9103 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9105 // The current behavior is similar to C++ lambdas. A block might be
9106 // assigned to a variable iff its return type and parameters are compatible
9107 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9108 // an assignment. Presumably it should behave in way that a function pointer
9109 // assignment does in C, so for each parameter and return type:
9110 // * CVR and address space of LHS should be a superset of CVR and address
9112 // * unqualified types should be compatible.
9113 if (S
.getLangOpts().OpenCL
) {
9114 if (!S
.Context
.typesAreBlockPointerCompatible(
9115 S
.Context
.getQualifiedType(LHSType
.getUnqualifiedType(), LQuals
),
9116 S
.Context
.getQualifiedType(RHSType
.getUnqualifiedType(), RQuals
)))
9117 return Sema::IncompatibleBlockPointer
;
9118 } else if (!S
.Context
.typesAreBlockPointerCompatible(LHSType
, RHSType
))
9119 return Sema::IncompatibleBlockPointer
;
9124 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9125 /// for assignment compatibility.
9126 static Sema::AssignConvertType
9127 checkObjCPointerTypesForAssignment(Sema
&S
, QualType LHSType
,
9129 assert(LHSType
.isCanonical() && "LHS was not canonicalized!");
9130 assert(RHSType
.isCanonical() && "RHS was not canonicalized!");
9132 if (LHSType
->isObjCBuiltinType()) {
9133 // Class is not compatible with ObjC object pointers.
9134 if (LHSType
->isObjCClassType() && !RHSType
->isObjCBuiltinType() &&
9135 !RHSType
->isObjCQualifiedClassType())
9136 return Sema::IncompatiblePointer
;
9137 return Sema::Compatible
;
9139 if (RHSType
->isObjCBuiltinType()) {
9140 if (RHSType
->isObjCClassType() && !LHSType
->isObjCBuiltinType() &&
9141 !LHSType
->isObjCQualifiedClassType())
9142 return Sema::IncompatiblePointer
;
9143 return Sema::Compatible
;
9145 QualType lhptee
= LHSType
->castAs
<ObjCObjectPointerType
>()->getPointeeType();
9146 QualType rhptee
= RHSType
->castAs
<ObjCObjectPointerType
>()->getPointeeType();
9148 if (!lhptee
.isAtLeastAsQualifiedAs(rhptee
, S
.getASTContext()) &&
9149 // make an exception for id<P>
9150 !LHSType
->isObjCQualifiedIdType())
9151 return Sema::CompatiblePointerDiscardsQualifiers
;
9153 if (S
.Context
.typesAreCompatible(LHSType
, RHSType
))
9154 return Sema::Compatible
;
9155 if (LHSType
->isObjCQualifiedIdType() || RHSType
->isObjCQualifiedIdType())
9156 return Sema::IncompatibleObjCQualifiedId
;
9157 return Sema::IncompatiblePointer
;
9160 Sema::AssignConvertType
9161 Sema::CheckAssignmentConstraints(SourceLocation Loc
,
9162 QualType LHSType
, QualType RHSType
) {
9163 // Fake up an opaque expression. We don't actually care about what
9164 // cast operations are required, so if CheckAssignmentConstraints
9165 // adds casts to this they'll be wasted, but fortunately that doesn't
9166 // usually happen on valid code.
9167 OpaqueValueExpr
RHSExpr(Loc
, RHSType
, VK_PRValue
);
9168 ExprResult RHSPtr
= &RHSExpr
;
9171 return CheckAssignmentConstraints(LHSType
, RHSPtr
, K
, /*ConvertRHS=*/false);
9174 /// This helper function returns true if QT is a vector type that has element
9175 /// type ElementType.
9176 static bool isVector(QualType QT
, QualType ElementType
) {
9177 if (const VectorType
*VT
= QT
->getAs
<VectorType
>())
9178 return VT
->getElementType().getCanonicalType() == ElementType
;
9182 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9183 /// has code to accommodate several GCC extensions when type checking
9184 /// pointers. Here are some objectionable examples that GCC considers warnings:
9188 /// struct foo *pfoo;
9190 /// pint = pshort; // warning: assignment from incompatible pointer type
9191 /// a = pint; // warning: assignment makes integer from pointer without a cast
9192 /// pint = a; // warning: assignment makes pointer from integer without a cast
9193 /// pint = pfoo; // warning: assignment from incompatible pointer type
9195 /// As a result, the code for dealing with pointers is more complex than the
9196 /// C99 spec dictates.
9198 /// Sets 'Kind' for any result kind except Incompatible.
9199 Sema::AssignConvertType
9200 Sema::CheckAssignmentConstraints(QualType LHSType
, ExprResult
&RHS
,
9201 CastKind
&Kind
, bool ConvertRHS
) {
9202 QualType RHSType
= RHS
.get()->getType();
9203 QualType OrigLHSType
= LHSType
;
9205 // Get canonical types. We're not formatting these types, just comparing
9207 LHSType
= Context
.getCanonicalType(LHSType
).getUnqualifiedType();
9208 RHSType
= Context
.getCanonicalType(RHSType
).getUnqualifiedType();
9210 // Common case: no conversion required.
9211 if (LHSType
== RHSType
) {
9216 // If the LHS has an __auto_type, there are no additional type constraints
9217 // to be worried about.
9218 if (const auto *AT
= dyn_cast
<AutoType
>(LHSType
)) {
9219 if (AT
->isGNUAutoType()) {
9225 // If we have an atomic type, try a non-atomic assignment, then just add an
9226 // atomic qualification step.
9227 if (const AtomicType
*AtomicTy
= dyn_cast
<AtomicType
>(LHSType
)) {
9228 Sema::AssignConvertType result
=
9229 CheckAssignmentConstraints(AtomicTy
->getValueType(), RHS
, Kind
);
9230 if (result
!= Compatible
)
9232 if (Kind
!= CK_NoOp
&& ConvertRHS
)
9233 RHS
= ImpCastExprToType(RHS
.get(), AtomicTy
->getValueType(), Kind
);
9234 Kind
= CK_NonAtomicToAtomic
;
9238 // If the left-hand side is a reference type, then we are in a
9239 // (rare!) case where we've allowed the use of references in C,
9240 // e.g., as a parameter type in a built-in function. In this case,
9241 // just make sure that the type referenced is compatible with the
9242 // right-hand side type. The caller is responsible for adjusting
9243 // LHSType so that the resulting expression does not have reference
9245 if (const ReferenceType
*LHSTypeRef
= LHSType
->getAs
<ReferenceType
>()) {
9246 if (Context
.typesAreCompatible(LHSTypeRef
->getPointeeType(), RHSType
)) {
9247 Kind
= CK_LValueBitCast
;
9250 return Incompatible
;
9253 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9254 // to the same ExtVector type.
9255 if (LHSType
->isExtVectorType()) {
9256 if (RHSType
->isExtVectorType())
9257 return Incompatible
;
9258 if (RHSType
->isArithmeticType()) {
9259 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9261 RHS
= prepareVectorSplat(LHSType
, RHS
.get());
9262 Kind
= CK_VectorSplat
;
9267 // Conversions to or from vector type.
9268 if (LHSType
->isVectorType() || RHSType
->isVectorType()) {
9269 if (LHSType
->isVectorType() && RHSType
->isVectorType()) {
9270 // Allow assignments of an AltiVec vector type to an equivalent GCC
9271 // vector type and vice versa
9272 if (Context
.areCompatibleVectorTypes(LHSType
, RHSType
)) {
9277 // If we are allowing lax vector conversions, and LHS and RHS are both
9278 // vectors, the total size only needs to be the same. This is a bitcast;
9279 // no bits are changed but the result type is different.
9280 if (isLaxVectorConversion(RHSType
, LHSType
)) {
9281 // The default for lax vector conversions with Altivec vectors will
9282 // change, so if we are converting between vector types where
9283 // at least one is an Altivec vector, emit a warning.
9284 if (Context
.getTargetInfo().getTriple().isPPC() &&
9285 anyAltivecTypes(RHSType
, LHSType
) &&
9286 !Context
.areCompatibleVectorTypes(RHSType
, LHSType
))
9287 Diag(RHS
.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all
)
9288 << RHSType
<< LHSType
;
9290 return IncompatibleVectors
;
9294 // When the RHS comes from another lax conversion (e.g. binops between
9295 // scalars and vectors) the result is canonicalized as a vector. When the
9296 // LHS is also a vector, the lax is allowed by the condition above. Handle
9297 // the case where LHS is a scalar.
9298 if (LHSType
->isScalarType()) {
9299 const VectorType
*VecType
= RHSType
->getAs
<VectorType
>();
9300 if (VecType
&& VecType
->getNumElements() == 1 &&
9301 isLaxVectorConversion(RHSType
, LHSType
)) {
9302 if (Context
.getTargetInfo().getTriple().isPPC() &&
9303 (VecType
->getVectorKind() == VectorKind::AltiVecVector
||
9304 VecType
->getVectorKind() == VectorKind::AltiVecBool
||
9305 VecType
->getVectorKind() == VectorKind::AltiVecPixel
))
9306 Diag(RHS
.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all
)
9307 << RHSType
<< LHSType
;
9308 ExprResult
*VecExpr
= &RHS
;
9309 *VecExpr
= ImpCastExprToType(VecExpr
->get(), LHSType
, CK_BitCast
);
9315 // Allow assignments between fixed-length and sizeless SVE vectors.
9316 if ((LHSType
->isSVESizelessBuiltinType() && RHSType
->isVectorType()) ||
9317 (LHSType
->isVectorType() && RHSType
->isSVESizelessBuiltinType()))
9318 if (Context
.areCompatibleSveTypes(LHSType
, RHSType
) ||
9319 Context
.areLaxCompatibleSveTypes(LHSType
, RHSType
)) {
9324 // Allow assignments between fixed-length and sizeless RVV vectors.
9325 if ((LHSType
->isRVVSizelessBuiltinType() && RHSType
->isVectorType()) ||
9326 (LHSType
->isVectorType() && RHSType
->isRVVSizelessBuiltinType())) {
9327 if (Context
.areCompatibleRVVTypes(LHSType
, RHSType
) ||
9328 Context
.areLaxCompatibleRVVTypes(LHSType
, RHSType
)) {
9334 return Incompatible
;
9337 // Diagnose attempts to convert between __ibm128, __float128 and long double
9338 // where such conversions currently can't be handled.
9339 if (unsupportedTypeConversion(*this, LHSType
, RHSType
))
9340 return Incompatible
;
9342 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9343 // discards the imaginary part.
9344 if (getLangOpts().CPlusPlus
&& RHSType
->getAs
<ComplexType
>() &&
9345 !LHSType
->getAs
<ComplexType
>())
9346 return Incompatible
;
9348 // Arithmetic conversions.
9349 if (LHSType
->isArithmeticType() && RHSType
->isArithmeticType() &&
9350 !(getLangOpts().CPlusPlus
&& LHSType
->isEnumeralType())) {
9352 Kind
= PrepareScalarCast(RHS
, LHSType
);
9356 // Conversions to normal pointers.
9357 if (const PointerType
*LHSPointer
= dyn_cast
<PointerType
>(LHSType
)) {
9359 if (isa
<PointerType
>(RHSType
)) {
9360 LangAS AddrSpaceL
= LHSPointer
->getPointeeType().getAddressSpace();
9361 LangAS AddrSpaceR
= RHSType
->getPointeeType().getAddressSpace();
9362 if (AddrSpaceL
!= AddrSpaceR
)
9363 Kind
= CK_AddressSpaceConversion
;
9364 else if (Context
.hasCvrSimilarType(RHSType
, LHSType
))
9368 return checkPointerTypesForAssignment(*this, LHSType
, RHSType
,
9369 RHS
.get()->getBeginLoc());
9373 if (RHSType
->isIntegerType()) {
9374 Kind
= CK_IntegralToPointer
; // FIXME: null?
9375 return IntToPointer
;
9378 // C pointers are not compatible with ObjC object pointers,
9379 // with two exceptions:
9380 if (isa
<ObjCObjectPointerType
>(RHSType
)) {
9381 // - conversions to void*
9382 if (LHSPointer
->getPointeeType()->isVoidType()) {
9387 // - conversions from 'Class' to the redefinition type
9388 if (RHSType
->isObjCClassType() &&
9389 Context
.hasSameType(LHSType
,
9390 Context
.getObjCClassRedefinitionType())) {
9396 return IncompatiblePointer
;
9400 if (RHSType
->getAs
<BlockPointerType
>()) {
9401 if (LHSPointer
->getPointeeType()->isVoidType()) {
9402 LangAS AddrSpaceL
= LHSPointer
->getPointeeType().getAddressSpace();
9403 LangAS AddrSpaceR
= RHSType
->getAs
<BlockPointerType
>()
9407 AddrSpaceL
!= AddrSpaceR
? CK_AddressSpaceConversion
: CK_BitCast
;
9412 return Incompatible
;
9415 // Conversions to block pointers.
9416 if (isa
<BlockPointerType
>(LHSType
)) {
9418 if (RHSType
->isBlockPointerType()) {
9419 LangAS AddrSpaceL
= LHSType
->getAs
<BlockPointerType
>()
9422 LangAS AddrSpaceR
= RHSType
->getAs
<BlockPointerType
>()
9425 Kind
= AddrSpaceL
!= AddrSpaceR
? CK_AddressSpaceConversion
: CK_BitCast
;
9426 return checkBlockPointerTypesForAssignment(*this, LHSType
, RHSType
);
9429 // int or null -> T^
9430 if (RHSType
->isIntegerType()) {
9431 Kind
= CK_IntegralToPointer
; // FIXME: null
9432 return IntToBlockPointer
;
9436 if (getLangOpts().ObjC
&& RHSType
->isObjCIdType()) {
9437 Kind
= CK_AnyPointerToBlockPointerCast
;
9442 if (const PointerType
*RHSPT
= RHSType
->getAs
<PointerType
>())
9443 if (RHSPT
->getPointeeType()->isVoidType()) {
9444 Kind
= CK_AnyPointerToBlockPointerCast
;
9448 return Incompatible
;
9451 // Conversions to Objective-C pointers.
9452 if (isa
<ObjCObjectPointerType
>(LHSType
)) {
9454 if (RHSType
->isObjCObjectPointerType()) {
9456 Sema::AssignConvertType result
=
9457 checkObjCPointerTypesForAssignment(*this, LHSType
, RHSType
);
9458 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9459 result
== Compatible
&&
9460 !ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType
, RHSType
))
9461 result
= IncompatibleObjCWeakRef
;
9465 // int or null -> A*
9466 if (RHSType
->isIntegerType()) {
9467 Kind
= CK_IntegralToPointer
; // FIXME: null
9468 return IntToPointer
;
9471 // In general, C pointers are not compatible with ObjC object pointers,
9472 // with two exceptions:
9473 if (isa
<PointerType
>(RHSType
)) {
9474 Kind
= CK_CPointerToObjCPointerCast
;
9476 // - conversions from 'void*'
9477 if (RHSType
->isVoidPointerType()) {
9481 // - conversions to 'Class' from its redefinition type
9482 if (LHSType
->isObjCClassType() &&
9483 Context
.hasSameType(RHSType
,
9484 Context
.getObjCClassRedefinitionType())) {
9488 return IncompatiblePointer
;
9491 // Only under strict condition T^ is compatible with an Objective-C pointer.
9492 if (RHSType
->isBlockPointerType() &&
9493 LHSType
->isBlockCompatibleObjCPointerType(Context
)) {
9495 maybeExtendBlockObject(RHS
);
9496 Kind
= CK_BlockPointerToObjCPointerCast
;
9500 return Incompatible
;
9503 // Conversion to nullptr_t (C23 only)
9504 if (getLangOpts().C23
&& LHSType
->isNullPtrType() &&
9505 RHS
.get()->isNullPointerConstant(Context
,
9506 Expr::NPC_ValueDependentIsNull
)) {
9507 // null -> nullptr_t
9508 Kind
= CK_NullToPointer
;
9512 // Conversions from pointers that are not covered by the above.
9513 if (isa
<PointerType
>(RHSType
)) {
9515 if (LHSType
== Context
.BoolTy
) {
9516 Kind
= CK_PointerToBoolean
;
9521 if (LHSType
->isIntegerType()) {
9522 Kind
= CK_PointerToIntegral
;
9523 return PointerToInt
;
9526 return Incompatible
;
9529 // Conversions from Objective-C pointers that are not covered by the above.
9530 if (isa
<ObjCObjectPointerType
>(RHSType
)) {
9532 if (LHSType
== Context
.BoolTy
) {
9533 Kind
= CK_PointerToBoolean
;
9538 if (LHSType
->isIntegerType()) {
9539 Kind
= CK_PointerToIntegral
;
9540 return PointerToInt
;
9543 return Incompatible
;
9546 // struct A -> struct B
9547 if (isa
<TagType
>(LHSType
) && isa
<TagType
>(RHSType
)) {
9548 if (Context
.typesAreCompatible(LHSType
, RHSType
)) {
9554 if (LHSType
->isSamplerT() && RHSType
->isIntegerType()) {
9555 Kind
= CK_IntToOCLSampler
;
9559 return Incompatible
;
9562 /// Constructs a transparent union from an expression that is
9563 /// used to initialize the transparent union.
9564 static void ConstructTransparentUnion(Sema
&S
, ASTContext
&C
,
9565 ExprResult
&EResult
, QualType UnionType
,
9567 // Build an initializer list that designates the appropriate member
9568 // of the transparent union.
9569 Expr
*E
= EResult
.get();
9570 InitListExpr
*Initializer
= new (C
) InitListExpr(C
, SourceLocation(),
9571 E
, SourceLocation());
9572 Initializer
->setType(UnionType
);
9573 Initializer
->setInitializedFieldInUnion(Field
);
9575 // Build a compound literal constructing a value of the transparent
9576 // union type from this initializer list.
9577 TypeSourceInfo
*unionTInfo
= C
.getTrivialTypeSourceInfo(UnionType
);
9578 EResult
= new (C
) CompoundLiteralExpr(SourceLocation(), unionTInfo
, UnionType
,
9579 VK_PRValue
, Initializer
, false);
9582 Sema::AssignConvertType
9583 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType
,
9585 QualType RHSType
= RHS
.get()->getType();
9587 // If the ArgType is a Union type, we want to handle a potential
9588 // transparent_union GCC extension.
9589 const RecordType
*UT
= ArgType
->getAsUnionType();
9590 if (!UT
|| !UT
->getDecl()->hasAttr
<TransparentUnionAttr
>())
9591 return Incompatible
;
9593 // The field to initialize within the transparent union.
9594 RecordDecl
*UD
= UT
->getDecl();
9595 FieldDecl
*InitField
= nullptr;
9596 // It's compatible if the expression matches any of the fields.
9597 for (auto *it
: UD
->fields()) {
9598 if (it
->getType()->isPointerType()) {
9599 // If the transparent union contains a pointer type, we allow:
9601 // 2) null pointer constant
9602 if (RHSType
->isPointerType())
9603 if (RHSType
->castAs
<PointerType
>()->getPointeeType()->isVoidType()) {
9604 RHS
= ImpCastExprToType(RHS
.get(), it
->getType(), CK_BitCast
);
9609 if (RHS
.get()->isNullPointerConstant(Context
,
9610 Expr::NPC_ValueDependentIsNull
)) {
9611 RHS
= ImpCastExprToType(RHS
.get(), it
->getType(),
9619 if (CheckAssignmentConstraints(it
->getType(), RHS
, Kind
)
9621 RHS
= ImpCastExprToType(RHS
.get(), it
->getType(), Kind
);
9628 return Incompatible
;
9630 ConstructTransparentUnion(*this, Context
, RHS
, ArgType
, InitField
);
9634 Sema::AssignConvertType
9635 Sema::CheckSingleAssignmentConstraints(QualType LHSType
, ExprResult
&CallerRHS
,
9637 bool DiagnoseCFAudited
,
9639 // We need to be able to tell the caller whether we diagnosed a problem, if
9640 // they ask us to issue diagnostics.
9641 assert((ConvertRHS
|| !Diagnose
) && "can't indicate whether we diagnosed");
9643 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9644 // we can't avoid *all* modifications at the moment, so we need some somewhere
9645 // to put the updated value.
9646 ExprResult LocalRHS
= CallerRHS
;
9647 ExprResult
&RHS
= ConvertRHS
? CallerRHS
: LocalRHS
;
9649 if (const auto *LHSPtrType
= LHSType
->getAs
<PointerType
>()) {
9650 if (const auto *RHSPtrType
= RHS
.get()->getType()->getAs
<PointerType
>()) {
9651 if (RHSPtrType
->getPointeeType()->hasAttr(attr::NoDeref
) &&
9652 !LHSPtrType
->getPointeeType()->hasAttr(attr::NoDeref
)) {
9653 Diag(RHS
.get()->getExprLoc(),
9654 diag::warn_noderef_to_dereferenceable_pointer
)
9655 << RHS
.get()->getSourceRange();
9660 if (getLangOpts().CPlusPlus
) {
9661 if (!LHSType
->isRecordType() && !LHSType
->isAtomicType()) {
9662 // C++ 5.17p3: If the left operand is not of class type, the
9663 // expression is implicitly converted (C++ 4) to the
9664 // cv-unqualified type of the left operand.
9665 QualType RHSType
= RHS
.get()->getType();
9667 RHS
= PerformImplicitConversion(RHS
.get(), LHSType
.getUnqualifiedType(),
9668 AssignmentAction::Assigning
);
9670 ImplicitConversionSequence ICS
=
9671 TryImplicitConversion(RHS
.get(), LHSType
.getUnqualifiedType(),
9672 /*SuppressUserConversions=*/false,
9673 AllowedExplicit::None
,
9674 /*InOverloadResolution=*/false,
9676 /*AllowObjCWritebackConversion=*/false);
9677 if (ICS
.isFailure())
9678 return Incompatible
;
9679 RHS
= PerformImplicitConversion(RHS
.get(), LHSType
.getUnqualifiedType(),
9680 ICS
, AssignmentAction::Assigning
);
9682 if (RHS
.isInvalid())
9683 return Incompatible
;
9684 Sema::AssignConvertType result
= Compatible
;
9685 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9686 !ObjC().CheckObjCARCUnavailableWeakConversion(LHSType
, RHSType
))
9687 result
= IncompatibleObjCWeakRef
;
9691 // FIXME: Currently, we fall through and treat C++ classes like C
9693 // FIXME: We also fall through for atomics; not sure what should
9694 // happen there, though.
9695 } else if (RHS
.get()->getType() == Context
.OverloadTy
) {
9696 // As a set of extensions to C, we support overloading on functions. These
9697 // functions need to be resolved here.
9699 if (FunctionDecl
*FD
= ResolveAddressOfOverloadedFunction(
9700 RHS
.get(), LHSType
, /*Complain=*/false, DAP
))
9701 RHS
= FixOverloadedFunctionReference(RHS
.get(), DAP
, FD
);
9703 return Incompatible
;
9706 // This check seems unnatural, however it is necessary to ensure the proper
9707 // conversion of functions/arrays. If the conversion were done for all
9708 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9709 // expressions that suppress this implicit conversion (&, sizeof). This needs
9710 // to happen before we check for null pointer conversions because C does not
9711 // undergo the same implicit conversions as C++ does above (by the calls to
9712 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
9713 // lvalue to rvalue cast before checking for null pointer constraints. This
9714 // addresses code like: nullptr_t val; int *ptr; ptr = val;
9716 // Suppress this for references: C++ 8.5.3p5.
9717 if (!LHSType
->isReferenceType()) {
9718 // FIXME: We potentially allocate here even if ConvertRHS is false.
9719 RHS
= DefaultFunctionArrayLvalueConversion(RHS
.get(), Diagnose
);
9720 if (RHS
.isInvalid())
9721 return Incompatible
;
9724 // The constraints are expressed in terms of the atomic, qualified, or
9725 // unqualified type of the LHS.
9726 QualType LHSTypeAfterConversion
= LHSType
.getAtomicUnqualifiedType();
9728 // C99 6.5.16.1p1: the left operand is a pointer and the right is
9729 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
9730 if ((LHSTypeAfterConversion
->isPointerType() ||
9731 LHSTypeAfterConversion
->isObjCObjectPointerType() ||
9732 LHSTypeAfterConversion
->isBlockPointerType()) &&
9733 ((getLangOpts().C23
&& RHS
.get()->getType()->isNullPtrType()) ||
9734 RHS
.get()->isNullPointerConstant(Context
,
9735 Expr::NPC_ValueDependentIsNull
))) {
9736 if (Diagnose
|| ConvertRHS
) {
9739 CheckPointerConversion(RHS
.get(), LHSType
, Kind
, Path
,
9740 /*IgnoreBaseAccess=*/false, Diagnose
);
9742 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, Kind
, VK_PRValue
, &Path
);
9746 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
9747 // unqualified bool, and the right operand is a pointer or its type is
9749 if (getLangOpts().C23
&& LHSType
->isBooleanType() &&
9750 RHS
.get()->getType()->isNullPtrType()) {
9751 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
9752 // only handles nullptr -> _Bool due to needing an extra conversion
9754 // We model this by converting from nullptr -> void * and then let the
9755 // conversion from void * -> _Bool happen naturally.
9756 if (Diagnose
|| ConvertRHS
) {
9759 CheckPointerConversion(RHS
.get(), Context
.VoidPtrTy
, Kind
, Path
,
9760 /*IgnoreBaseAccess=*/false, Diagnose
);
9762 RHS
= ImpCastExprToType(RHS
.get(), Context
.VoidPtrTy
, Kind
, VK_PRValue
,
9767 // OpenCL queue_t type assignment.
9768 if (LHSType
->isQueueT() && RHS
.get()->isNullPointerConstant(
9769 Context
, Expr::NPC_ValueDependentIsNull
)) {
9770 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_NullToPointer
);
9775 Sema::AssignConvertType result
=
9776 CheckAssignmentConstraints(LHSType
, RHS
, Kind
, ConvertRHS
);
9778 // C99 6.5.16.1p2: The value of the right operand is converted to the
9779 // type of the assignment expression.
9780 // CheckAssignmentConstraints allows the left-hand side to be a reference,
9781 // so that we can use references in built-in functions even in C.
9782 // The getNonReferenceType() call makes sure that the resulting expression
9783 // does not have reference type.
9784 if (result
!= Incompatible
&& RHS
.get()->getType() != LHSType
) {
9785 QualType Ty
= LHSType
.getNonLValueExprType(Context
);
9786 Expr
*E
= RHS
.get();
9788 // Check for various Objective-C errors. If we are not reporting
9789 // diagnostics and just checking for errors, e.g., during overload
9790 // resolution, return Incompatible to indicate the failure.
9791 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9792 ObjC().CheckObjCConversion(SourceRange(), Ty
, E
,
9793 CheckedConversionKind::Implicit
, Diagnose
,
9794 DiagnoseCFAudited
) != SemaObjC::ACR_okay
) {
9796 return Incompatible
;
9798 if (getLangOpts().ObjC
&&
9799 (ObjC().CheckObjCBridgeRelatedConversions(E
->getBeginLoc(), LHSType
,
9800 E
->getType(), E
, Diagnose
) ||
9801 ObjC().CheckConversionToObjCLiteral(LHSType
, E
, Diagnose
))) {
9803 return Incompatible
;
9804 // Replace the expression with a corrected version and continue so we
9805 // can find further errors.
9811 RHS
= ImpCastExprToType(E
, Ty
, Kind
);
9818 /// The original operand to an operator, prior to the application of the usual
9819 /// arithmetic conversions and converting the arguments of a builtin operator
9821 struct OriginalOperand
{
9822 explicit OriginalOperand(Expr
*Op
) : Orig(Op
), Conversion(nullptr) {
9823 if (auto *MTE
= dyn_cast
<MaterializeTemporaryExpr
>(Op
))
9824 Op
= MTE
->getSubExpr();
9825 if (auto *BTE
= dyn_cast
<CXXBindTemporaryExpr
>(Op
))
9826 Op
= BTE
->getSubExpr();
9827 if (auto *ICE
= dyn_cast
<ImplicitCastExpr
>(Op
)) {
9828 Orig
= ICE
->getSubExprAsWritten();
9829 Conversion
= ICE
->getConversionFunction();
9833 QualType
getType() const { return Orig
->getType(); }
9836 NamedDecl
*Conversion
;
9840 QualType
Sema::InvalidOperands(SourceLocation Loc
, ExprResult
&LHS
,
9842 OriginalOperand
OrigLHS(LHS
.get()), OrigRHS(RHS
.get());
9844 Diag(Loc
, diag::err_typecheck_invalid_operands
)
9845 << OrigLHS
.getType() << OrigRHS
.getType()
9846 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
9848 // If a user-defined conversion was applied to either of the operands prior
9849 // to applying the built-in operator rules, tell the user about it.
9850 if (OrigLHS
.Conversion
) {
9851 Diag(OrigLHS
.Conversion
->getLocation(),
9852 diag::note_typecheck_invalid_operands_converted
)
9853 << 0 << LHS
.get()->getType();
9855 if (OrigRHS
.Conversion
) {
9856 Diag(OrigRHS
.Conversion
->getLocation(),
9857 diag::note_typecheck_invalid_operands_converted
)
9858 << 1 << RHS
.get()->getType();
9864 QualType
Sema::InvalidLogicalVectorOperands(SourceLocation Loc
, ExprResult
&LHS
,
9866 QualType LHSType
= LHS
.get()->IgnoreImpCasts()->getType();
9867 QualType RHSType
= RHS
.get()->IgnoreImpCasts()->getType();
9869 bool LHSNatVec
= LHSType
->isVectorType();
9870 bool RHSNatVec
= RHSType
->isVectorType();
9872 if (!(LHSNatVec
&& RHSNatVec
)) {
9873 Expr
*Vector
= LHSNatVec
? LHS
.get() : RHS
.get();
9874 Expr
*NonVector
= !LHSNatVec
? LHS
.get() : RHS
.get();
9875 Diag(Loc
, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict
)
9876 << 0 << Vector
->getType() << NonVector
->IgnoreImpCasts()->getType()
9877 << Vector
->getSourceRange();
9881 Diag(Loc
, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict
)
9882 << 1 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
9883 << RHS
.get()->getSourceRange();
9888 /// Try to convert a value of non-vector type to a vector type by converting
9889 /// the type to the element type of the vector and then performing a splat.
9890 /// If the language is OpenCL, we only use conversions that promote scalar
9891 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9894 /// OpenCL V2.0 6.2.6.p2:
9895 /// An error shall occur if any scalar operand type has greater rank
9896 /// than the type of the vector element.
9898 /// \param scalar - if non-null, actually perform the conversions
9899 /// \return true if the operation fails (but without diagnosing the failure)
9900 static bool tryVectorConvertAndSplat(Sema
&S
, ExprResult
*scalar
,
9902 QualType vectorEltTy
,
9905 // The conversion to apply to the scalar before splatting it,
9907 CastKind scalarCast
= CK_NoOp
;
9909 if (vectorEltTy
->isBooleanType() && scalarTy
->isIntegralType(S
.Context
)) {
9910 scalarCast
= CK_IntegralToBoolean
;
9911 } else if (vectorEltTy
->isIntegralType(S
.Context
)) {
9912 if (S
.getLangOpts().OpenCL
&& (scalarTy
->isRealFloatingType() ||
9913 (scalarTy
->isIntegerType() &&
9914 S
.Context
.getIntegerTypeOrder(vectorEltTy
, scalarTy
) < 0))) {
9915 DiagID
= diag::err_opencl_scalar_type_rank_greater_than_vector_type
;
9918 if (!scalarTy
->isIntegralType(S
.Context
))
9920 scalarCast
= CK_IntegralCast
;
9921 } else if (vectorEltTy
->isRealFloatingType()) {
9922 if (scalarTy
->isRealFloatingType()) {
9923 if (S
.getLangOpts().OpenCL
&&
9924 S
.Context
.getFloatingTypeOrder(vectorEltTy
, scalarTy
) < 0) {
9925 DiagID
= diag::err_opencl_scalar_type_rank_greater_than_vector_type
;
9928 scalarCast
= CK_FloatingCast
;
9930 else if (scalarTy
->isIntegralType(S
.Context
))
9931 scalarCast
= CK_IntegralToFloating
;
9938 // Adjust scalar if desired.
9940 if (scalarCast
!= CK_NoOp
)
9941 *scalar
= S
.ImpCastExprToType(scalar
->get(), vectorEltTy
, scalarCast
);
9942 *scalar
= S
.ImpCastExprToType(scalar
->get(), vectorTy
, CK_VectorSplat
);
9947 /// Convert vector E to a vector with the same number of elements but different
9949 static ExprResult
convertVector(Expr
*E
, QualType ElementType
, Sema
&S
) {
9950 const auto *VecTy
= E
->getType()->getAs
<VectorType
>();
9951 assert(VecTy
&& "Expression E must be a vector");
9953 VecTy
->isExtVectorType()
9954 ? S
.Context
.getExtVectorType(ElementType
, VecTy
->getNumElements())
9955 : S
.Context
.getVectorType(ElementType
, VecTy
->getNumElements(),
9956 VecTy
->getVectorKind());
9958 // Look through the implicit cast. Return the subexpression if its type is
9960 if (auto *ICE
= dyn_cast
<ImplicitCastExpr
>(E
))
9961 if (ICE
->getSubExpr()->getType() == NewVecTy
)
9962 return ICE
->getSubExpr();
9964 auto Cast
= ElementType
->isIntegerType() ? CK_IntegralCast
: CK_FloatingCast
;
9965 return S
.ImpCastExprToType(E
, NewVecTy
, Cast
);
9968 /// Test if a (constant) integer Int can be casted to another integer type
9969 /// IntTy without losing precision.
9970 static bool canConvertIntToOtherIntTy(Sema
&S
, ExprResult
*Int
,
9971 QualType OtherIntTy
) {
9972 if (Int
->get()->containsErrors())
9975 QualType IntTy
= Int
->get()->getType().getUnqualifiedType();
9977 // Reject cases where the value of the Int is unknown as that would
9978 // possibly cause truncation, but accept cases where the scalar can be
9979 // demoted without loss of precision.
9980 Expr::EvalResult EVResult
;
9981 bool CstInt
= Int
->get()->EvaluateAsInt(EVResult
, S
.Context
);
9982 int Order
= S
.Context
.getIntegerTypeOrder(OtherIntTy
, IntTy
);
9983 bool IntSigned
= IntTy
->hasSignedIntegerRepresentation();
9984 bool OtherIntSigned
= OtherIntTy
->hasSignedIntegerRepresentation();
9987 // If the scalar is constant and is of a higher order and has more active
9988 // bits that the vector element type, reject it.
9989 llvm::APSInt Result
= EVResult
.Val
.getInt();
9990 unsigned NumBits
= IntSigned
9991 ? (Result
.isNegative() ? Result
.getSignificantBits()
9992 : Result
.getActiveBits())
9993 : Result
.getActiveBits();
9994 if (Order
< 0 && S
.Context
.getIntWidth(OtherIntTy
) < NumBits
)
9997 // If the signedness of the scalar type and the vector element type
9998 // differs and the number of bits is greater than that of the vector
9999 // element reject it.
10000 return (IntSigned
!= OtherIntSigned
&&
10001 NumBits
> S
.Context
.getIntWidth(OtherIntTy
));
10004 // Reject cases where the value of the scalar is not constant and it's
10005 // order is greater than that of the vector element type.
10006 return (Order
< 0);
10009 /// Test if a (constant) integer Int can be casted to floating point type
10010 /// FloatTy without losing precision.
10011 static bool canConvertIntTyToFloatTy(Sema
&S
, ExprResult
*Int
,
10012 QualType FloatTy
) {
10013 if (Int
->get()->containsErrors())
10016 QualType IntTy
= Int
->get()->getType().getUnqualifiedType();
10018 // Determine if the integer constant can be expressed as a floating point
10019 // number of the appropriate type.
10020 Expr::EvalResult EVResult
;
10021 bool CstInt
= Int
->get()->EvaluateAsInt(EVResult
, S
.Context
);
10025 // Reject constants that would be truncated if they were converted to
10026 // the floating point type. Test by simple to/from conversion.
10027 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10028 // could be avoided if there was a convertFromAPInt method
10029 // which could signal back if implicit truncation occurred.
10030 llvm::APSInt Result
= EVResult
.Val
.getInt();
10031 llvm::APFloat
Float(S
.Context
.getFloatTypeSemantics(FloatTy
));
10032 Float
.convertFromAPInt(Result
, IntTy
->hasSignedIntegerRepresentation(),
10033 llvm::APFloat::rmTowardZero
);
10034 llvm::APSInt
ConvertBack(S
.Context
.getIntWidth(IntTy
),
10035 !IntTy
->hasSignedIntegerRepresentation());
10036 bool Ignored
= false;
10037 Float
.convertToInteger(ConvertBack
, llvm::APFloat::rmNearestTiesToEven
,
10039 if (Result
!= ConvertBack
)
10042 // Reject types that cannot be fully encoded into the mantissa of
10044 Bits
= S
.Context
.getTypeSize(IntTy
);
10045 unsigned FloatPrec
= llvm::APFloat::semanticsPrecision(
10046 S
.Context
.getFloatTypeSemantics(FloatTy
));
10047 if (Bits
> FloatPrec
)
10054 /// Attempt to convert and splat Scalar into a vector whose types matches
10055 /// Vector following GCC conversion rules. The rule is that implicit
10056 /// conversion can occur when Scalar can be casted to match Vector's element
10057 /// type without causing truncation of Scalar.
10058 static bool tryGCCVectorConvertAndSplat(Sema
&S
, ExprResult
*Scalar
,
10059 ExprResult
*Vector
) {
10060 QualType ScalarTy
= Scalar
->get()->getType().getUnqualifiedType();
10061 QualType VectorTy
= Vector
->get()->getType().getUnqualifiedType();
10062 QualType VectorEltTy
;
10064 if (const auto *VT
= VectorTy
->getAs
<VectorType
>()) {
10065 assert(!isa
<ExtVectorType
>(VT
) &&
10066 "ExtVectorTypes should not be handled here!");
10067 VectorEltTy
= VT
->getElementType();
10068 } else if (VectorTy
->isSveVLSBuiltinType()) {
10070 VectorTy
->castAs
<BuiltinType
>()->getSveEltType(S
.getASTContext());
10072 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10075 // Reject cases where the vector element type or the scalar element type are
10076 // not integral or floating point types.
10077 if (!VectorEltTy
->isArithmeticType() || !ScalarTy
->isArithmeticType())
10080 // The conversion to apply to the scalar before splatting it,
10082 CastKind ScalarCast
= CK_NoOp
;
10084 // Accept cases where the vector elements are integers and the scalar is
10086 // FIXME: Notionally if the scalar was a floating point value with a precise
10087 // integral representation, we could cast it to an appropriate integer
10088 // type and then perform the rest of the checks here. GCC will perform
10089 // this conversion in some cases as determined by the input language.
10090 // We should accept it on a language independent basis.
10091 if (VectorEltTy
->isIntegralType(S
.Context
) &&
10092 ScalarTy
->isIntegralType(S
.Context
) &&
10093 S
.Context
.getIntegerTypeOrder(VectorEltTy
, ScalarTy
)) {
10095 if (canConvertIntToOtherIntTy(S
, Scalar
, VectorEltTy
))
10098 ScalarCast
= CK_IntegralCast
;
10099 } else if (VectorEltTy
->isIntegralType(S
.Context
) &&
10100 ScalarTy
->isRealFloatingType()) {
10101 if (S
.Context
.getTypeSize(VectorEltTy
) == S
.Context
.getTypeSize(ScalarTy
))
10102 ScalarCast
= CK_FloatingToIntegral
;
10105 } else if (VectorEltTy
->isRealFloatingType()) {
10106 if (ScalarTy
->isRealFloatingType()) {
10108 // Reject cases where the scalar type is not a constant and has a higher
10109 // Order than the vector element type.
10110 llvm::APFloat
Result(0.0);
10112 // Determine whether this is a constant scalar. In the event that the
10113 // value is dependent (and thus cannot be evaluated by the constant
10114 // evaluator), skip the evaluation. This will then diagnose once the
10115 // expression is instantiated.
10116 bool CstScalar
= Scalar
->get()->isValueDependent() ||
10117 Scalar
->get()->EvaluateAsFloat(Result
, S
.Context
);
10118 int Order
= S
.Context
.getFloatingTypeOrder(VectorEltTy
, ScalarTy
);
10119 if (!CstScalar
&& Order
< 0)
10122 // If the scalar cannot be safely casted to the vector element type,
10125 bool Truncated
= false;
10126 Result
.convert(S
.Context
.getFloatTypeSemantics(VectorEltTy
),
10127 llvm::APFloat::rmNearestTiesToEven
, &Truncated
);
10132 ScalarCast
= CK_FloatingCast
;
10133 } else if (ScalarTy
->isIntegralType(S
.Context
)) {
10134 if (canConvertIntTyToFloatTy(S
, Scalar
, VectorEltTy
))
10137 ScalarCast
= CK_IntegralToFloating
;
10140 } else if (ScalarTy
->isEnumeralType())
10143 // Adjust scalar if desired.
10144 if (ScalarCast
!= CK_NoOp
)
10145 *Scalar
= S
.ImpCastExprToType(Scalar
->get(), VectorEltTy
, ScalarCast
);
10146 *Scalar
= S
.ImpCastExprToType(Scalar
->get(), VectorTy
, CK_VectorSplat
);
10150 QualType
Sema::CheckVectorOperands(ExprResult
&LHS
, ExprResult
&RHS
,
10151 SourceLocation Loc
, bool IsCompAssign
,
10152 bool AllowBothBool
,
10153 bool AllowBoolConversions
,
10154 bool AllowBoolOperation
,
10155 bool ReportInvalid
) {
10156 if (!IsCompAssign
) {
10157 LHS
= DefaultFunctionArrayLvalueConversion(LHS
.get());
10158 if (LHS
.isInvalid())
10161 RHS
= DefaultFunctionArrayLvalueConversion(RHS
.get());
10162 if (RHS
.isInvalid())
10165 // For conversion purposes, we ignore any qualifiers.
10166 // For example, "const float" and "float" are equivalent.
10167 QualType LHSType
= LHS
.get()->getType().getUnqualifiedType();
10168 QualType RHSType
= RHS
.get()->getType().getUnqualifiedType();
10170 const VectorType
*LHSVecType
= LHSType
->getAs
<VectorType
>();
10171 const VectorType
*RHSVecType
= RHSType
->getAs
<VectorType
>();
10172 assert(LHSVecType
|| RHSVecType
);
10174 if (getLangOpts().HLSL
)
10175 return HLSL().handleVectorBinOpConversion(LHS
, RHS
, LHSType
, RHSType
,
10178 // AltiVec-style "vector bool op vector bool" combinations are allowed
10179 // for some operators but not others.
10180 if (!AllowBothBool
&& LHSVecType
&&
10181 LHSVecType
->getVectorKind() == VectorKind::AltiVecBool
&& RHSVecType
&&
10182 RHSVecType
->getVectorKind() == VectorKind::AltiVecBool
)
10183 return ReportInvalid
? InvalidOperands(Loc
, LHS
, RHS
) : QualType();
10185 // This operation may not be performed on boolean vectors.
10186 if (!AllowBoolOperation
&&
10187 (LHSType
->isExtVectorBoolType() || RHSType
->isExtVectorBoolType()))
10188 return ReportInvalid
? InvalidOperands(Loc
, LHS
, RHS
) : QualType();
10190 // If the vector types are identical, return.
10191 if (Context
.hasSameType(LHSType
, RHSType
))
10192 return Context
.getCommonSugaredType(LHSType
, RHSType
);
10194 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10195 if (LHSVecType
&& RHSVecType
&&
10196 Context
.areCompatibleVectorTypes(LHSType
, RHSType
)) {
10197 if (isa
<ExtVectorType
>(LHSVecType
)) {
10198 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_BitCast
);
10203 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_BitCast
);
10207 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10208 // can be mixed, with the result being the non-bool type. The non-bool
10209 // operand must have integer element type.
10210 if (AllowBoolConversions
&& LHSVecType
&& RHSVecType
&&
10211 LHSVecType
->getNumElements() == RHSVecType
->getNumElements() &&
10212 (Context
.getTypeSize(LHSVecType
->getElementType()) ==
10213 Context
.getTypeSize(RHSVecType
->getElementType()))) {
10214 if (LHSVecType
->getVectorKind() == VectorKind::AltiVecVector
&&
10215 LHSVecType
->getElementType()->isIntegerType() &&
10216 RHSVecType
->getVectorKind() == VectorKind::AltiVecBool
) {
10217 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_BitCast
);
10220 if (!IsCompAssign
&&
10221 LHSVecType
->getVectorKind() == VectorKind::AltiVecBool
&&
10222 RHSVecType
->getVectorKind() == VectorKind::AltiVecVector
&&
10223 RHSVecType
->getElementType()->isIntegerType()) {
10224 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_BitCast
);
10229 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10230 // invalid since the ambiguity can affect the ABI.
10231 auto IsSveRVVConversion
= [](QualType FirstType
, QualType SecondType
,
10232 unsigned &SVEorRVV
) {
10233 const VectorType
*VecType
= SecondType
->getAs
<VectorType
>();
10235 if (FirstType
->isSizelessBuiltinType() && VecType
) {
10236 if (VecType
->getVectorKind() == VectorKind::SveFixedLengthData
||
10237 VecType
->getVectorKind() == VectorKind::SveFixedLengthPredicate
)
10239 if (VecType
->getVectorKind() == VectorKind::RVVFixedLengthData
||
10240 VecType
->getVectorKind() == VectorKind::RVVFixedLengthMask
||
10241 VecType
->getVectorKind() == VectorKind::RVVFixedLengthMask_1
||
10242 VecType
->getVectorKind() == VectorKind::RVVFixedLengthMask_2
||
10243 VecType
->getVectorKind() == VectorKind::RVVFixedLengthMask_4
) {
10253 if (IsSveRVVConversion(LHSType
, RHSType
, SVEorRVV
) ||
10254 IsSveRVVConversion(RHSType
, LHSType
, SVEorRVV
)) {
10255 Diag(Loc
, diag::err_typecheck_sve_rvv_ambiguous
)
10256 << SVEorRVV
<< LHSType
<< RHSType
;
10260 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10261 // invalid since the ambiguity can affect the ABI.
10262 auto IsSveRVVGnuConversion
= [](QualType FirstType
, QualType SecondType
,
10263 unsigned &SVEorRVV
) {
10264 const VectorType
*FirstVecType
= FirstType
->getAs
<VectorType
>();
10265 const VectorType
*SecondVecType
= SecondType
->getAs
<VectorType
>();
10268 if (FirstVecType
&& SecondVecType
) {
10269 if (FirstVecType
->getVectorKind() == VectorKind::Generic
) {
10270 if (SecondVecType
->getVectorKind() == VectorKind::SveFixedLengthData
||
10271 SecondVecType
->getVectorKind() ==
10272 VectorKind::SveFixedLengthPredicate
)
10274 if (SecondVecType
->getVectorKind() == VectorKind::RVVFixedLengthData
||
10275 SecondVecType
->getVectorKind() == VectorKind::RVVFixedLengthMask
||
10276 SecondVecType
->getVectorKind() ==
10277 VectorKind::RVVFixedLengthMask_1
||
10278 SecondVecType
->getVectorKind() ==
10279 VectorKind::RVVFixedLengthMask_2
||
10280 SecondVecType
->getVectorKind() ==
10281 VectorKind::RVVFixedLengthMask_4
) {
10289 if (SecondVecType
&&
10290 SecondVecType
->getVectorKind() == VectorKind::Generic
) {
10291 if (FirstType
->isSVESizelessBuiltinType())
10293 if (FirstType
->isRVVSizelessBuiltinType()) {
10302 if (IsSveRVVGnuConversion(LHSType
, RHSType
, SVEorRVV
) ||
10303 IsSveRVVGnuConversion(RHSType
, LHSType
, SVEorRVV
)) {
10304 Diag(Loc
, diag::err_typecheck_sve_rvv_gnu_ambiguous
)
10305 << SVEorRVV
<< LHSType
<< RHSType
;
10309 // If there's a vector type and a scalar, try to convert the scalar to
10310 // the vector element type and splat.
10311 unsigned DiagID
= diag::err_typecheck_vector_not_convertable
;
10313 if (isa
<ExtVectorType
>(LHSVecType
)) {
10314 if (!tryVectorConvertAndSplat(*this, &RHS
, RHSType
,
10315 LHSVecType
->getElementType(), LHSType
,
10319 if (!tryGCCVectorConvertAndSplat(*this, &RHS
, &LHS
))
10324 if (isa
<ExtVectorType
>(RHSVecType
)) {
10325 if (!tryVectorConvertAndSplat(*this, (IsCompAssign
? nullptr : &LHS
),
10326 LHSType
, RHSVecType
->getElementType(),
10330 if (LHS
.get()->isLValue() ||
10331 !tryGCCVectorConvertAndSplat(*this, &LHS
, &RHS
))
10336 // FIXME: The code below also handles conversion between vectors and
10337 // non-scalars, we should break this down into fine grained specific checks
10338 // and emit proper diagnostics.
10339 QualType VecType
= LHSVecType
? LHSType
: RHSType
;
10340 const VectorType
*VT
= LHSVecType
? LHSVecType
: RHSVecType
;
10341 QualType OtherType
= LHSVecType
? RHSType
: LHSType
;
10342 ExprResult
*OtherExpr
= LHSVecType
? &RHS
: &LHS
;
10343 if (isLaxVectorConversion(OtherType
, VecType
)) {
10344 if (Context
.getTargetInfo().getTriple().isPPC() &&
10345 anyAltivecTypes(RHSType
, LHSType
) &&
10346 !Context
.areCompatibleVectorTypes(RHSType
, LHSType
))
10347 Diag(Loc
, diag::warn_deprecated_lax_vec_conv_all
) << RHSType
<< LHSType
;
10348 // If we're allowing lax vector conversions, only the total (data) size
10349 // needs to be the same. For non compound assignment, if one of the types is
10350 // scalar, the result is always the vector type.
10351 if (!IsCompAssign
) {
10352 *OtherExpr
= ImpCastExprToType(OtherExpr
->get(), VecType
, CK_BitCast
);
10354 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10355 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10356 // type. Note that this is already done by non-compound assignments in
10357 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10358 // <1 x T> -> T. The result is also a vector type.
10359 } else if (OtherType
->isExtVectorType() || OtherType
->isVectorType() ||
10360 (OtherType
->isScalarType() && VT
->getNumElements() == 1)) {
10361 ExprResult
*RHSExpr
= &RHS
;
10362 *RHSExpr
= ImpCastExprToType(RHSExpr
->get(), LHSType
, CK_BitCast
);
10367 // Okay, the expression is invalid.
10369 // If there's a non-vector, non-real operand, diagnose that.
10370 if ((!RHSVecType
&& !RHSType
->isRealType()) ||
10371 (!LHSVecType
&& !LHSType
->isRealType())) {
10372 Diag(Loc
, diag::err_typecheck_vector_not_convertable_non_scalar
)
10373 << LHSType
<< RHSType
10374 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
10378 // OpenCL V1.1 6.2.6.p1:
10379 // If the operands are of more than one vector type, then an error shall
10380 // occur. Implicit conversions between vector types are not permitted, per
10382 if (getLangOpts().OpenCL
&&
10383 RHSVecType
&& isa
<ExtVectorType
>(RHSVecType
) &&
10384 LHSVecType
&& isa
<ExtVectorType
>(LHSVecType
)) {
10385 Diag(Loc
, diag::err_opencl_implicit_vector_conversion
) << LHSType
10391 // If there is a vector type that is not a ExtVector and a scalar, we reach
10392 // this point if scalar could not be converted to the vector's element type
10393 // without truncation.
10394 if ((RHSVecType
&& !isa
<ExtVectorType
>(RHSVecType
)) ||
10395 (LHSVecType
&& !isa
<ExtVectorType
>(LHSVecType
))) {
10396 QualType Scalar
= LHSVecType
? RHSType
: LHSType
;
10397 QualType Vector
= LHSVecType
? LHSType
: RHSType
;
10398 unsigned ScalarOrVector
= LHSVecType
&& RHSVecType
? 1 : 0;
10400 diag::err_typecheck_vector_not_convertable_implict_truncation
)
10401 << ScalarOrVector
<< Scalar
<< Vector
;
10406 // Otherwise, use the generic diagnostic.
10408 << LHSType
<< RHSType
10409 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
10413 QualType
Sema::CheckSizelessVectorOperands(ExprResult
&LHS
, ExprResult
&RHS
,
10414 SourceLocation Loc
,
10416 ArithConvKind OperationKind
) {
10417 if (!IsCompAssign
) {
10418 LHS
= DefaultFunctionArrayLvalueConversion(LHS
.get());
10419 if (LHS
.isInvalid())
10422 RHS
= DefaultFunctionArrayLvalueConversion(RHS
.get());
10423 if (RHS
.isInvalid())
10426 QualType LHSType
= LHS
.get()->getType().getUnqualifiedType();
10427 QualType RHSType
= RHS
.get()->getType().getUnqualifiedType();
10429 const BuiltinType
*LHSBuiltinTy
= LHSType
->getAs
<BuiltinType
>();
10430 const BuiltinType
*RHSBuiltinTy
= RHSType
->getAs
<BuiltinType
>();
10432 unsigned DiagID
= diag::err_typecheck_invalid_operands
;
10433 if ((OperationKind
== ACK_Arithmetic
) &&
10434 ((LHSBuiltinTy
&& LHSBuiltinTy
->isSVEBool()) ||
10435 (RHSBuiltinTy
&& RHSBuiltinTy
->isSVEBool()))) {
10436 Diag(Loc
, DiagID
) << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
10437 << RHS
.get()->getSourceRange();
10441 if (Context
.hasSameType(LHSType
, RHSType
))
10444 if (LHSType
->isSveVLSBuiltinType() && !RHSType
->isSveVLSBuiltinType()) {
10445 if (!tryGCCVectorConvertAndSplat(*this, &RHS
, &LHS
))
10448 if (RHSType
->isSveVLSBuiltinType() && !LHSType
->isSveVLSBuiltinType()) {
10449 if (LHS
.get()->isLValue() ||
10450 !tryGCCVectorConvertAndSplat(*this, &LHS
, &RHS
))
10454 if ((!LHSType
->isSveVLSBuiltinType() && !LHSType
->isRealType()) ||
10455 (!RHSType
->isSveVLSBuiltinType() && !RHSType
->isRealType())) {
10456 Diag(Loc
, diag::err_typecheck_vector_not_convertable_non_scalar
)
10457 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
10458 << RHS
.get()->getSourceRange();
10462 if (LHSType
->isSveVLSBuiltinType() && RHSType
->isSveVLSBuiltinType() &&
10463 Context
.getBuiltinVectorTypeInfo(LHSBuiltinTy
).EC
!=
10464 Context
.getBuiltinVectorTypeInfo(RHSBuiltinTy
).EC
) {
10465 Diag(Loc
, diag::err_typecheck_vector_lengths_not_equal
)
10466 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
10467 << RHS
.get()->getSourceRange();
10471 if (LHSType
->isSveVLSBuiltinType() || RHSType
->isSveVLSBuiltinType()) {
10472 QualType Scalar
= LHSType
->isSveVLSBuiltinType() ? RHSType
: LHSType
;
10473 QualType Vector
= LHSType
->isSveVLSBuiltinType() ? LHSType
: RHSType
;
10474 bool ScalarOrVector
=
10475 LHSType
->isSveVLSBuiltinType() && RHSType
->isSveVLSBuiltinType();
10477 Diag(Loc
, diag::err_typecheck_vector_not_convertable_implict_truncation
)
10478 << ScalarOrVector
<< Scalar
<< Vector
;
10483 Diag(Loc
, DiagID
) << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
10484 << RHS
.get()->getSourceRange();
10488 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
10489 // expression. These are mainly cases where the null pointer is used as an
10490 // integer instead of a pointer.
10491 static void checkArithmeticNull(Sema
&S
, ExprResult
&LHS
, ExprResult
&RHS
,
10492 SourceLocation Loc
, bool IsCompare
) {
10493 // The canonical way to check for a GNU null is with isNullPointerConstant,
10494 // but we use a bit of a hack here for speed; this is a relatively
10495 // hot path, and isNullPointerConstant is slow.
10496 bool LHSNull
= isa
<GNUNullExpr
>(LHS
.get()->IgnoreParenImpCasts());
10497 bool RHSNull
= isa
<GNUNullExpr
>(RHS
.get()->IgnoreParenImpCasts());
10499 QualType NonNullType
= LHSNull
? RHS
.get()->getType() : LHS
.get()->getType();
10501 // Avoid analyzing cases where the result will either be invalid (and
10502 // diagnosed as such) or entirely valid and not something to warn about.
10503 if ((!LHSNull
&& !RHSNull
) || NonNullType
->isBlockPointerType() ||
10504 NonNullType
->isMemberPointerType() || NonNullType
->isFunctionType())
10507 // Comparison operations would not make sense with a null pointer no matter
10508 // what the other expression is.
10510 S
.Diag(Loc
, diag::warn_null_in_arithmetic_operation
)
10511 << (LHSNull
? LHS
.get()->getSourceRange() : SourceRange())
10512 << (RHSNull
? RHS
.get()->getSourceRange() : SourceRange());
10516 // The rest of the operations only make sense with a null pointer
10517 // if the other expression is a pointer.
10518 if (LHSNull
== RHSNull
|| NonNullType
->isAnyPointerType() ||
10519 NonNullType
->canDecayToPointerType())
10522 S
.Diag(Loc
, diag::warn_null_in_comparison_operation
)
10523 << LHSNull
/* LHS is NULL */ << NonNullType
10524 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
10527 static void DiagnoseDivisionSizeofPointerOrArray(Sema
&S
, Expr
*LHS
, Expr
*RHS
,
10528 SourceLocation Loc
) {
10529 const auto *LUE
= dyn_cast
<UnaryExprOrTypeTraitExpr
>(LHS
);
10530 const auto *RUE
= dyn_cast
<UnaryExprOrTypeTraitExpr
>(RHS
);
10533 if (LUE
->getKind() != UETT_SizeOf
|| LUE
->isArgumentType() ||
10534 RUE
->getKind() != UETT_SizeOf
)
10537 const Expr
*LHSArg
= LUE
->getArgumentExpr()->IgnoreParens();
10538 QualType LHSTy
= LHSArg
->getType();
10541 if (RUE
->isArgumentType())
10542 RHSTy
= RUE
->getArgumentType().getNonReferenceType();
10544 RHSTy
= RUE
->getArgumentExpr()->IgnoreParens()->getType();
10546 if (LHSTy
->isPointerType() && !RHSTy
->isPointerType()) {
10547 if (!S
.Context
.hasSameUnqualifiedType(LHSTy
->getPointeeType(), RHSTy
))
10550 S
.Diag(Loc
, diag::warn_division_sizeof_ptr
) << LHS
<< LHS
->getSourceRange();
10551 if (const auto *DRE
= dyn_cast
<DeclRefExpr
>(LHSArg
)) {
10552 if (const ValueDecl
*LHSArgDecl
= DRE
->getDecl())
10553 S
.Diag(LHSArgDecl
->getLocation(), diag::note_pointer_declared_here
)
10556 } else if (const auto *ArrayTy
= S
.Context
.getAsArrayType(LHSTy
)) {
10557 QualType ArrayElemTy
= ArrayTy
->getElementType();
10558 if (ArrayElemTy
!= S
.Context
.getBaseElementType(ArrayTy
) ||
10559 ArrayElemTy
->isDependentType() || RHSTy
->isDependentType() ||
10560 RHSTy
->isReferenceType() || ArrayElemTy
->isCharType() ||
10561 S
.Context
.getTypeSize(ArrayElemTy
) == S
.Context
.getTypeSize(RHSTy
))
10563 S
.Diag(Loc
, diag::warn_division_sizeof_array
)
10564 << LHSArg
->getSourceRange() << ArrayElemTy
<< RHSTy
;
10565 if (const auto *DRE
= dyn_cast
<DeclRefExpr
>(LHSArg
)) {
10566 if (const ValueDecl
*LHSArgDecl
= DRE
->getDecl())
10567 S
.Diag(LHSArgDecl
->getLocation(), diag::note_array_declared_here
)
10571 S
.Diag(Loc
, diag::note_precedence_silence
) << RHS
;
10575 static void DiagnoseBadDivideOrRemainderValues(Sema
& S
, ExprResult
&LHS
,
10577 SourceLocation Loc
, bool IsDiv
) {
10578 // Check for division/remainder by zero.
10579 Expr::EvalResult RHSValue
;
10580 if (!RHS
.get()->isValueDependent() &&
10581 RHS
.get()->EvaluateAsInt(RHSValue
, S
.Context
) &&
10582 RHSValue
.Val
.getInt() == 0)
10583 S
.DiagRuntimeBehavior(Loc
, RHS
.get(),
10584 S
.PDiag(diag::warn_remainder_division_by_zero
)
10585 << IsDiv
<< RHS
.get()->getSourceRange());
10588 QualType
Sema::CheckMultiplyDivideOperands(ExprResult
&LHS
, ExprResult
&RHS
,
10589 SourceLocation Loc
,
10590 bool IsCompAssign
, bool IsDiv
) {
10591 checkArithmeticNull(*this, LHS
, RHS
, Loc
, /*IsCompare=*/false);
10593 QualType LHSTy
= LHS
.get()->getType();
10594 QualType RHSTy
= RHS
.get()->getType();
10595 if (LHSTy
->isVectorType() || RHSTy
->isVectorType())
10596 return CheckVectorOperands(LHS
, RHS
, Loc
, IsCompAssign
,
10597 /*AllowBothBool*/ getLangOpts().AltiVec
,
10598 /*AllowBoolConversions*/ false,
10599 /*AllowBooleanOperation*/ false,
10600 /*ReportInvalid*/ true);
10601 if (LHSTy
->isSveVLSBuiltinType() || RHSTy
->isSveVLSBuiltinType())
10602 return CheckSizelessVectorOperands(LHS
, RHS
, Loc
, IsCompAssign
,
10605 (LHSTy
->isConstantMatrixType() || RHSTy
->isConstantMatrixType()))
10606 return CheckMatrixMultiplyOperands(LHS
, RHS
, Loc
, IsCompAssign
);
10607 // For division, only matrix-by-scalar is supported. Other combinations with
10608 // matrix types are invalid.
10609 if (IsDiv
&& LHSTy
->isConstantMatrixType() && RHSTy
->isArithmeticType())
10610 return CheckMatrixElementwiseOperands(LHS
, RHS
, Loc
, IsCompAssign
);
10612 QualType compType
= UsualArithmeticConversions(
10613 LHS
, RHS
, Loc
, IsCompAssign
? ACK_CompAssign
: ACK_Arithmetic
);
10614 if (LHS
.isInvalid() || RHS
.isInvalid())
10618 if (compType
.isNull() || !compType
->isArithmeticType())
10619 return InvalidOperands(Loc
, LHS
, RHS
);
10621 DiagnoseBadDivideOrRemainderValues(*this, LHS
, RHS
, Loc
, IsDiv
);
10622 DiagnoseDivisionSizeofPointerOrArray(*this, LHS
.get(), RHS
.get(), Loc
);
10627 QualType
Sema::CheckRemainderOperands(
10628 ExprResult
&LHS
, ExprResult
&RHS
, SourceLocation Loc
, bool IsCompAssign
) {
10629 checkArithmeticNull(*this, LHS
, RHS
, Loc
, /*IsCompare=*/false);
10631 if (LHS
.get()->getType()->isVectorType() ||
10632 RHS
.get()->getType()->isVectorType()) {
10633 if (LHS
.get()->getType()->hasIntegerRepresentation() &&
10634 RHS
.get()->getType()->hasIntegerRepresentation())
10635 return CheckVectorOperands(LHS
, RHS
, Loc
, IsCompAssign
,
10636 /*AllowBothBool*/ getLangOpts().AltiVec
,
10637 /*AllowBoolConversions*/ false,
10638 /*AllowBooleanOperation*/ false,
10639 /*ReportInvalid*/ true);
10640 return InvalidOperands(Loc
, LHS
, RHS
);
10643 if (LHS
.get()->getType()->isSveVLSBuiltinType() ||
10644 RHS
.get()->getType()->isSveVLSBuiltinType()) {
10645 if (LHS
.get()->getType()->hasIntegerRepresentation() &&
10646 RHS
.get()->getType()->hasIntegerRepresentation())
10647 return CheckSizelessVectorOperands(LHS
, RHS
, Loc
, IsCompAssign
,
10650 return InvalidOperands(Loc
, LHS
, RHS
);
10653 QualType compType
= UsualArithmeticConversions(
10654 LHS
, RHS
, Loc
, IsCompAssign
? ACK_CompAssign
: ACK_Arithmetic
);
10655 if (LHS
.isInvalid() || RHS
.isInvalid())
10658 if (compType
.isNull() || !compType
->isIntegerType())
10659 return InvalidOperands(Loc
, LHS
, RHS
);
10660 DiagnoseBadDivideOrRemainderValues(*this, LHS
, RHS
, Loc
, false /* IsDiv */);
10664 /// Diagnose invalid arithmetic on two void pointers.
10665 static void diagnoseArithmeticOnTwoVoidPointers(Sema
&S
, SourceLocation Loc
,
10666 Expr
*LHSExpr
, Expr
*RHSExpr
) {
10667 S
.Diag(Loc
, S
.getLangOpts().CPlusPlus
10668 ? diag::err_typecheck_pointer_arith_void_type
10669 : diag::ext_gnu_void_ptr
)
10670 << 1 /* two pointers */ << LHSExpr
->getSourceRange()
10671 << RHSExpr
->getSourceRange();
10674 /// Diagnose invalid arithmetic on a void pointer.
10675 static void diagnoseArithmeticOnVoidPointer(Sema
&S
, SourceLocation Loc
,
10677 S
.Diag(Loc
, S
.getLangOpts().CPlusPlus
10678 ? diag::err_typecheck_pointer_arith_void_type
10679 : diag::ext_gnu_void_ptr
)
10680 << 0 /* one pointer */ << Pointer
->getSourceRange();
10683 /// Diagnose invalid arithmetic on a null pointer.
10685 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10686 /// idiom, which we recognize as a GNU extension.
10688 static void diagnoseArithmeticOnNullPointer(Sema
&S
, SourceLocation Loc
,
10689 Expr
*Pointer
, bool IsGNUIdiom
) {
10691 S
.Diag(Loc
, diag::warn_gnu_null_ptr_arith
)
10692 << Pointer
->getSourceRange();
10694 S
.Diag(Loc
, diag::warn_pointer_arith_null_ptr
)
10695 << S
.getLangOpts().CPlusPlus
<< Pointer
->getSourceRange();
10698 /// Diagnose invalid subraction on a null pointer.
10700 static void diagnoseSubtractionOnNullPointer(Sema
&S
, SourceLocation Loc
,
10701 Expr
*Pointer
, bool BothNull
) {
10702 // Null - null is valid in C++ [expr.add]p7
10703 if (BothNull
&& S
.getLangOpts().CPlusPlus
)
10706 // Is this s a macro from a system header?
10707 if (S
.Diags
.getSuppressSystemWarnings() && S
.SourceMgr
.isInSystemMacro(Loc
))
10710 S
.DiagRuntimeBehavior(Loc
, Pointer
,
10711 S
.PDiag(diag::warn_pointer_sub_null_ptr
)
10712 << S
.getLangOpts().CPlusPlus
10713 << Pointer
->getSourceRange());
10716 /// Diagnose invalid arithmetic on two function pointers.
10717 static void diagnoseArithmeticOnTwoFunctionPointers(Sema
&S
, SourceLocation Loc
,
10718 Expr
*LHS
, Expr
*RHS
) {
10719 assert(LHS
->getType()->isAnyPointerType());
10720 assert(RHS
->getType()->isAnyPointerType());
10721 S
.Diag(Loc
, S
.getLangOpts().CPlusPlus
10722 ? diag::err_typecheck_pointer_arith_function_type
10723 : diag::ext_gnu_ptr_func_arith
)
10724 << 1 /* two pointers */ << LHS
->getType()->getPointeeType()
10725 // We only show the second type if it differs from the first.
10726 << (unsigned)!S
.Context
.hasSameUnqualifiedType(LHS
->getType(),
10728 << RHS
->getType()->getPointeeType()
10729 << LHS
->getSourceRange() << RHS
->getSourceRange();
10732 /// Diagnose invalid arithmetic on a function pointer.
10733 static void diagnoseArithmeticOnFunctionPointer(Sema
&S
, SourceLocation Loc
,
10735 assert(Pointer
->getType()->isAnyPointerType());
10736 S
.Diag(Loc
, S
.getLangOpts().CPlusPlus
10737 ? diag::err_typecheck_pointer_arith_function_type
10738 : diag::ext_gnu_ptr_func_arith
)
10739 << 0 /* one pointer */ << Pointer
->getType()->getPointeeType()
10740 << 0 /* one pointer, so only one type */
10741 << Pointer
->getSourceRange();
10744 /// Emit error if Operand is incomplete pointer type
10746 /// \returns True if pointer has incomplete type
10747 static bool checkArithmeticIncompletePointerType(Sema
&S
, SourceLocation Loc
,
10749 QualType ResType
= Operand
->getType();
10750 if (const AtomicType
*ResAtomicType
= ResType
->getAs
<AtomicType
>())
10751 ResType
= ResAtomicType
->getValueType();
10753 assert(ResType
->isAnyPointerType());
10754 QualType PointeeTy
= ResType
->getPointeeType();
10755 return S
.RequireCompleteSizedType(
10757 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type
,
10758 Operand
->getSourceRange());
10761 /// Check the validity of an arithmetic pointer operand.
10763 /// If the operand has pointer type, this code will check for pointer types
10764 /// which are invalid in arithmetic operations. These will be diagnosed
10765 /// appropriately, including whether or not the use is supported as an
10768 /// \returns True when the operand is valid to use (even if as an extension).
10769 static bool checkArithmeticOpPointerOperand(Sema
&S
, SourceLocation Loc
,
10771 QualType ResType
= Operand
->getType();
10772 if (const AtomicType
*ResAtomicType
= ResType
->getAs
<AtomicType
>())
10773 ResType
= ResAtomicType
->getValueType();
10775 if (!ResType
->isAnyPointerType()) return true;
10777 QualType PointeeTy
= ResType
->getPointeeType();
10778 if (PointeeTy
->isVoidType()) {
10779 diagnoseArithmeticOnVoidPointer(S
, Loc
, Operand
);
10780 return !S
.getLangOpts().CPlusPlus
;
10782 if (PointeeTy
->isFunctionType()) {
10783 diagnoseArithmeticOnFunctionPointer(S
, Loc
, Operand
);
10784 return !S
.getLangOpts().CPlusPlus
;
10787 if (checkArithmeticIncompletePointerType(S
, Loc
, Operand
)) return false;
10792 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10795 /// This routine will diagnose any invalid arithmetic on pointer operands much
10796 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10797 /// for emitting a single diagnostic even for operations where both LHS and RHS
10798 /// are (potentially problematic) pointers.
10800 /// \returns True when the operand is valid to use (even if as an extension).
10801 static bool checkArithmeticBinOpPointerOperands(Sema
&S
, SourceLocation Loc
,
10802 Expr
*LHSExpr
, Expr
*RHSExpr
) {
10803 bool isLHSPointer
= LHSExpr
->getType()->isAnyPointerType();
10804 bool isRHSPointer
= RHSExpr
->getType()->isAnyPointerType();
10805 if (!isLHSPointer
&& !isRHSPointer
) return true;
10807 QualType LHSPointeeTy
, RHSPointeeTy
;
10808 if (isLHSPointer
) LHSPointeeTy
= LHSExpr
->getType()->getPointeeType();
10809 if (isRHSPointer
) RHSPointeeTy
= RHSExpr
->getType()->getPointeeType();
10811 // if both are pointers check if operation is valid wrt address spaces
10812 if (isLHSPointer
&& isRHSPointer
) {
10813 if (!LHSPointeeTy
.isAddressSpaceOverlapping(RHSPointeeTy
,
10814 S
.getASTContext())) {
10816 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers
)
10817 << LHSExpr
->getType() << RHSExpr
->getType() << 1 /*arithmetic op*/
10818 << LHSExpr
->getSourceRange() << RHSExpr
->getSourceRange();
10823 // Check for arithmetic on pointers to incomplete types.
10824 bool isLHSVoidPtr
= isLHSPointer
&& LHSPointeeTy
->isVoidType();
10825 bool isRHSVoidPtr
= isRHSPointer
&& RHSPointeeTy
->isVoidType();
10826 if (isLHSVoidPtr
|| isRHSVoidPtr
) {
10827 if (!isRHSVoidPtr
) diagnoseArithmeticOnVoidPointer(S
, Loc
, LHSExpr
);
10828 else if (!isLHSVoidPtr
) diagnoseArithmeticOnVoidPointer(S
, Loc
, RHSExpr
);
10829 else diagnoseArithmeticOnTwoVoidPointers(S
, Loc
, LHSExpr
, RHSExpr
);
10831 return !S
.getLangOpts().CPlusPlus
;
10834 bool isLHSFuncPtr
= isLHSPointer
&& LHSPointeeTy
->isFunctionType();
10835 bool isRHSFuncPtr
= isRHSPointer
&& RHSPointeeTy
->isFunctionType();
10836 if (isLHSFuncPtr
|| isRHSFuncPtr
) {
10837 if (!isRHSFuncPtr
) diagnoseArithmeticOnFunctionPointer(S
, Loc
, LHSExpr
);
10838 else if (!isLHSFuncPtr
) diagnoseArithmeticOnFunctionPointer(S
, Loc
,
10840 else diagnoseArithmeticOnTwoFunctionPointers(S
, Loc
, LHSExpr
, RHSExpr
);
10842 return !S
.getLangOpts().CPlusPlus
;
10845 if (isLHSPointer
&& checkArithmeticIncompletePointerType(S
, Loc
, LHSExpr
))
10847 if (isRHSPointer
&& checkArithmeticIncompletePointerType(S
, Loc
, RHSExpr
))
10853 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10855 static void diagnoseStringPlusInt(Sema
&Self
, SourceLocation OpLoc
,
10856 Expr
*LHSExpr
, Expr
*RHSExpr
) {
10857 StringLiteral
* StrExpr
= dyn_cast
<StringLiteral
>(LHSExpr
->IgnoreImpCasts());
10858 Expr
* IndexExpr
= RHSExpr
;
10860 StrExpr
= dyn_cast
<StringLiteral
>(RHSExpr
->IgnoreImpCasts());
10861 IndexExpr
= LHSExpr
;
10864 bool IsStringPlusInt
= StrExpr
&&
10865 IndexExpr
->getType()->isIntegralOrUnscopedEnumerationType();
10866 if (!IsStringPlusInt
|| IndexExpr
->isValueDependent())
10869 SourceRange
DiagRange(LHSExpr
->getBeginLoc(), RHSExpr
->getEndLoc());
10870 Self
.Diag(OpLoc
, diag::warn_string_plus_int
)
10871 << DiagRange
<< IndexExpr
->IgnoreImpCasts()->getType();
10873 // Only print a fixit for "str" + int, not for int + "str".
10874 if (IndexExpr
== RHSExpr
) {
10875 SourceLocation EndLoc
= Self
.getLocForEndOfToken(RHSExpr
->getEndLoc());
10876 Self
.Diag(OpLoc
, diag::note_string_plus_scalar_silence
)
10877 << FixItHint::CreateInsertion(LHSExpr
->getBeginLoc(), "&")
10878 << FixItHint::CreateReplacement(SourceRange(OpLoc
), "[")
10879 << FixItHint::CreateInsertion(EndLoc
, "]");
10881 Self
.Diag(OpLoc
, diag::note_string_plus_scalar_silence
);
10884 /// Emit a warning when adding a char literal to a string.
10885 static void diagnoseStringPlusChar(Sema
&Self
, SourceLocation OpLoc
,
10886 Expr
*LHSExpr
, Expr
*RHSExpr
) {
10887 const Expr
*StringRefExpr
= LHSExpr
;
10888 const CharacterLiteral
*CharExpr
=
10889 dyn_cast
<CharacterLiteral
>(RHSExpr
->IgnoreImpCasts());
10892 CharExpr
= dyn_cast
<CharacterLiteral
>(LHSExpr
->IgnoreImpCasts());
10893 StringRefExpr
= RHSExpr
;
10896 if (!CharExpr
|| !StringRefExpr
)
10899 const QualType StringType
= StringRefExpr
->getType();
10901 // Return if not a PointerType.
10902 if (!StringType
->isAnyPointerType())
10905 // Return if not a CharacterType.
10906 if (!StringType
->getPointeeType()->isAnyCharacterType())
10909 ASTContext
&Ctx
= Self
.getASTContext();
10910 SourceRange
DiagRange(LHSExpr
->getBeginLoc(), RHSExpr
->getEndLoc());
10912 const QualType CharType
= CharExpr
->getType();
10913 if (!CharType
->isAnyCharacterType() &&
10914 CharType
->isIntegerType() &&
10915 llvm::isUIntN(Ctx
.getCharWidth(), CharExpr
->getValue())) {
10916 Self
.Diag(OpLoc
, diag::warn_string_plus_char
)
10917 << DiagRange
<< Ctx
.CharTy
;
10919 Self
.Diag(OpLoc
, diag::warn_string_plus_char
)
10920 << DiagRange
<< CharExpr
->getType();
10923 // Only print a fixit for str + char, not for char + str.
10924 if (isa
<CharacterLiteral
>(RHSExpr
->IgnoreImpCasts())) {
10925 SourceLocation EndLoc
= Self
.getLocForEndOfToken(RHSExpr
->getEndLoc());
10926 Self
.Diag(OpLoc
, diag::note_string_plus_scalar_silence
)
10927 << FixItHint::CreateInsertion(LHSExpr
->getBeginLoc(), "&")
10928 << FixItHint::CreateReplacement(SourceRange(OpLoc
), "[")
10929 << FixItHint::CreateInsertion(EndLoc
, "]");
10931 Self
.Diag(OpLoc
, diag::note_string_plus_scalar_silence
);
10935 /// Emit error when two pointers are incompatible.
10936 static void diagnosePointerIncompatibility(Sema
&S
, SourceLocation Loc
,
10937 Expr
*LHSExpr
, Expr
*RHSExpr
) {
10938 assert(LHSExpr
->getType()->isAnyPointerType());
10939 assert(RHSExpr
->getType()->isAnyPointerType());
10940 S
.Diag(Loc
, diag::err_typecheck_sub_ptr_compatible
)
10941 << LHSExpr
->getType() << RHSExpr
->getType() << LHSExpr
->getSourceRange()
10942 << RHSExpr
->getSourceRange();
10946 QualType
Sema::CheckAdditionOperands(ExprResult
&LHS
, ExprResult
&RHS
,
10947 SourceLocation Loc
, BinaryOperatorKind Opc
,
10948 QualType
* CompLHSTy
) {
10949 checkArithmeticNull(*this, LHS
, RHS
, Loc
, /*IsCompare=*/false);
10951 if (LHS
.get()->getType()->isVectorType() ||
10952 RHS
.get()->getType()->isVectorType()) {
10953 QualType compType
=
10954 CheckVectorOperands(LHS
, RHS
, Loc
, CompLHSTy
,
10955 /*AllowBothBool*/ getLangOpts().AltiVec
,
10956 /*AllowBoolConversions*/ getLangOpts().ZVector
,
10957 /*AllowBooleanOperation*/ false,
10958 /*ReportInvalid*/ true);
10959 if (CompLHSTy
) *CompLHSTy
= compType
;
10963 if (LHS
.get()->getType()->isSveVLSBuiltinType() ||
10964 RHS
.get()->getType()->isSveVLSBuiltinType()) {
10965 QualType compType
=
10966 CheckSizelessVectorOperands(LHS
, RHS
, Loc
, CompLHSTy
, ACK_Arithmetic
);
10968 *CompLHSTy
= compType
;
10972 if (LHS
.get()->getType()->isConstantMatrixType() ||
10973 RHS
.get()->getType()->isConstantMatrixType()) {
10974 QualType compType
=
10975 CheckMatrixElementwiseOperands(LHS
, RHS
, Loc
, CompLHSTy
);
10977 *CompLHSTy
= compType
;
10981 QualType compType
= UsualArithmeticConversions(
10982 LHS
, RHS
, Loc
, CompLHSTy
? ACK_CompAssign
: ACK_Arithmetic
);
10983 if (LHS
.isInvalid() || RHS
.isInvalid())
10986 // Diagnose "string literal" '+' int and string '+' "char literal".
10987 if (Opc
== BO_Add
) {
10988 diagnoseStringPlusInt(*this, Loc
, LHS
.get(), RHS
.get());
10989 diagnoseStringPlusChar(*this, Loc
, LHS
.get(), RHS
.get());
10992 // handle the common case first (both operands are arithmetic).
10993 if (!compType
.isNull() && compType
->isArithmeticType()) {
10994 if (CompLHSTy
) *CompLHSTy
= compType
;
10998 // Type-checking. Ultimately the pointer's going to be in PExp;
10999 // note that we bias towards the LHS being the pointer.
11000 Expr
*PExp
= LHS
.get(), *IExp
= RHS
.get();
11002 bool isObjCPointer
;
11003 if (PExp
->getType()->isPointerType()) {
11004 isObjCPointer
= false;
11005 } else if (PExp
->getType()->isObjCObjectPointerType()) {
11006 isObjCPointer
= true;
11008 std::swap(PExp
, IExp
);
11009 if (PExp
->getType()->isPointerType()) {
11010 isObjCPointer
= false;
11011 } else if (PExp
->getType()->isObjCObjectPointerType()) {
11012 isObjCPointer
= true;
11014 return InvalidOperands(Loc
, LHS
, RHS
);
11017 assert(PExp
->getType()->isAnyPointerType());
11019 if (!IExp
->getType()->isIntegerType())
11020 return InvalidOperands(Loc
, LHS
, RHS
);
11022 // Adding to a null pointer results in undefined behavior.
11023 if (PExp
->IgnoreParenCasts()->isNullPointerConstant(
11024 Context
, Expr::NPC_ValueDependentIsNotNull
)) {
11025 // In C++ adding zero to a null pointer is defined.
11026 Expr::EvalResult KnownVal
;
11027 if (!getLangOpts().CPlusPlus
||
11028 (!IExp
->isValueDependent() &&
11029 (!IExp
->EvaluateAsInt(KnownVal
, Context
) ||
11030 KnownVal
.Val
.getInt() != 0))) {
11031 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11032 bool IsGNUIdiom
= BinaryOperator::isNullPointerArithmeticExtension(
11033 Context
, BO_Add
, PExp
, IExp
);
11034 diagnoseArithmeticOnNullPointer(*this, Loc
, PExp
, IsGNUIdiom
);
11038 if (!checkArithmeticOpPointerOperand(*this, Loc
, PExp
))
11041 if (isObjCPointer
&& checkArithmeticOnObjCPointer(*this, Loc
, PExp
))
11044 // Arithmetic on label addresses is normally allowed, except when we add
11045 // a ptrauth signature to the addresses.
11046 if (isa
<AddrLabelExpr
>(PExp
) && getLangOpts().PointerAuthIndirectGotos
) {
11047 Diag(Loc
, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic
)
11052 // Check array bounds for pointer arithemtic
11053 CheckArrayAccess(PExp
, IExp
);
11056 QualType LHSTy
= Context
.isPromotableBitField(LHS
.get());
11057 if (LHSTy
.isNull()) {
11058 LHSTy
= LHS
.get()->getType();
11059 if (Context
.isPromotableIntegerType(LHSTy
))
11060 LHSTy
= Context
.getPromotedIntegerType(LHSTy
);
11062 *CompLHSTy
= LHSTy
;
11065 return PExp
->getType();
11069 QualType
Sema::CheckSubtractionOperands(ExprResult
&LHS
, ExprResult
&RHS
,
11070 SourceLocation Loc
,
11071 QualType
* CompLHSTy
) {
11072 checkArithmeticNull(*this, LHS
, RHS
, Loc
, /*IsCompare=*/false);
11074 if (LHS
.get()->getType()->isVectorType() ||
11075 RHS
.get()->getType()->isVectorType()) {
11076 QualType compType
=
11077 CheckVectorOperands(LHS
, RHS
, Loc
, CompLHSTy
,
11078 /*AllowBothBool*/ getLangOpts().AltiVec
,
11079 /*AllowBoolConversions*/ getLangOpts().ZVector
,
11080 /*AllowBooleanOperation*/ false,
11081 /*ReportInvalid*/ true);
11082 if (CompLHSTy
) *CompLHSTy
= compType
;
11086 if (LHS
.get()->getType()->isSveVLSBuiltinType() ||
11087 RHS
.get()->getType()->isSveVLSBuiltinType()) {
11088 QualType compType
=
11089 CheckSizelessVectorOperands(LHS
, RHS
, Loc
, CompLHSTy
, ACK_Arithmetic
);
11091 *CompLHSTy
= compType
;
11095 if (LHS
.get()->getType()->isConstantMatrixType() ||
11096 RHS
.get()->getType()->isConstantMatrixType()) {
11097 QualType compType
=
11098 CheckMatrixElementwiseOperands(LHS
, RHS
, Loc
, CompLHSTy
);
11100 *CompLHSTy
= compType
;
11104 QualType compType
= UsualArithmeticConversions(
11105 LHS
, RHS
, Loc
, CompLHSTy
? ACK_CompAssign
: ACK_Arithmetic
);
11106 if (LHS
.isInvalid() || RHS
.isInvalid())
11109 // Enforce type constraints: C99 6.5.6p3.
11111 // Handle the common case first (both operands are arithmetic).
11112 if (!compType
.isNull() && compType
->isArithmeticType()) {
11113 if (CompLHSTy
) *CompLHSTy
= compType
;
11117 // Either ptr - int or ptr - ptr.
11118 if (LHS
.get()->getType()->isAnyPointerType()) {
11119 QualType lpointee
= LHS
.get()->getType()->getPointeeType();
11121 // Diagnose bad cases where we step over interface counts.
11122 if (LHS
.get()->getType()->isObjCObjectPointerType() &&
11123 checkArithmeticOnObjCPointer(*this, Loc
, LHS
.get()))
11126 // Arithmetic on label addresses is normally allowed, except when we add
11127 // a ptrauth signature to the addresses.
11128 if (isa
<AddrLabelExpr
>(LHS
.get()) &&
11129 getLangOpts().PointerAuthIndirectGotos
) {
11130 Diag(Loc
, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic
)
11131 << /*subtraction*/ 0;
11135 // The result type of a pointer-int computation is the pointer type.
11136 if (RHS
.get()->getType()->isIntegerType()) {
11137 // Subtracting from a null pointer should produce a warning.
11138 // The last argument to the diagnose call says this doesn't match the
11139 // GNU int-to-pointer idiom.
11140 if (LHS
.get()->IgnoreParenCasts()->isNullPointerConstant(Context
,
11141 Expr::NPC_ValueDependentIsNotNull
)) {
11142 // In C++ adding zero to a null pointer is defined.
11143 Expr::EvalResult KnownVal
;
11144 if (!getLangOpts().CPlusPlus
||
11145 (!RHS
.get()->isValueDependent() &&
11146 (!RHS
.get()->EvaluateAsInt(KnownVal
, Context
) ||
11147 KnownVal
.Val
.getInt() != 0))) {
11148 diagnoseArithmeticOnNullPointer(*this, Loc
, LHS
.get(), false);
11152 if (!checkArithmeticOpPointerOperand(*this, Loc
, LHS
.get()))
11155 // Check array bounds for pointer arithemtic
11156 CheckArrayAccess(LHS
.get(), RHS
.get(), /*ArraySubscriptExpr*/nullptr,
11157 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11159 if (CompLHSTy
) *CompLHSTy
= LHS
.get()->getType();
11160 return LHS
.get()->getType();
11163 // Handle pointer-pointer subtractions.
11164 if (const PointerType
*RHSPTy
11165 = RHS
.get()->getType()->getAs
<PointerType
>()) {
11166 QualType rpointee
= RHSPTy
->getPointeeType();
11168 if (getLangOpts().CPlusPlus
) {
11169 // Pointee types must be the same: C++ [expr.add]
11170 if (!Context
.hasSameUnqualifiedType(lpointee
, rpointee
)) {
11171 diagnosePointerIncompatibility(*this, Loc
, LHS
.get(), RHS
.get());
11174 // Pointee types must be compatible C99 6.5.6p3
11175 if (!Context
.typesAreCompatible(
11176 Context
.getCanonicalType(lpointee
).getUnqualifiedType(),
11177 Context
.getCanonicalType(rpointee
).getUnqualifiedType())) {
11178 diagnosePointerIncompatibility(*this, Loc
, LHS
.get(), RHS
.get());
11183 if (!checkArithmeticBinOpPointerOperands(*this, Loc
,
11184 LHS
.get(), RHS
.get()))
11187 bool LHSIsNullPtr
= LHS
.get()->IgnoreParenCasts()->isNullPointerConstant(
11188 Context
, Expr::NPC_ValueDependentIsNotNull
);
11189 bool RHSIsNullPtr
= RHS
.get()->IgnoreParenCasts()->isNullPointerConstant(
11190 Context
, Expr::NPC_ValueDependentIsNotNull
);
11192 // Subtracting nullptr or from nullptr is suspect
11194 diagnoseSubtractionOnNullPointer(*this, Loc
, LHS
.get(), RHSIsNullPtr
);
11196 diagnoseSubtractionOnNullPointer(*this, Loc
, RHS
.get(), LHSIsNullPtr
);
11198 // The pointee type may have zero size. As an extension, a structure or
11199 // union may have zero size or an array may have zero length. In this
11200 // case subtraction does not make sense.
11201 if (!rpointee
->isVoidType() && !rpointee
->isFunctionType()) {
11202 CharUnits ElementSize
= Context
.getTypeSizeInChars(rpointee
);
11203 if (ElementSize
.isZero()) {
11204 Diag(Loc
,diag::warn_sub_ptr_zero_size_types
)
11205 << rpointee
.getUnqualifiedType()
11206 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
11210 if (CompLHSTy
) *CompLHSTy
= LHS
.get()->getType();
11211 return Context
.getPointerDiffType();
11215 return InvalidOperands(Loc
, LHS
, RHS
);
11218 static bool isScopedEnumerationType(QualType T
) {
11219 if (const EnumType
*ET
= T
->getAs
<EnumType
>())
11220 return ET
->getDecl()->isScoped();
11224 static void DiagnoseBadShiftValues(Sema
& S
, ExprResult
&LHS
, ExprResult
&RHS
,
11225 SourceLocation Loc
, BinaryOperatorKind Opc
,
11226 QualType LHSType
) {
11227 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11228 // so skip remaining warnings as we don't want to modify values within Sema.
11229 if (S
.getLangOpts().OpenCL
)
11232 // Check right/shifter operand
11233 Expr::EvalResult RHSResult
;
11234 if (RHS
.get()->isValueDependent() ||
11235 !RHS
.get()->EvaluateAsInt(RHSResult
, S
.Context
))
11237 llvm::APSInt Right
= RHSResult
.Val
.getInt();
11239 if (Right
.isNegative()) {
11240 S
.DiagRuntimeBehavior(Loc
, RHS
.get(),
11241 S
.PDiag(diag::warn_shift_negative
)
11242 << RHS
.get()->getSourceRange());
11246 QualType LHSExprType
= LHS
.get()->getType();
11247 uint64_t LeftSize
= S
.Context
.getTypeSize(LHSExprType
);
11248 if (LHSExprType
->isBitIntType())
11249 LeftSize
= S
.Context
.getIntWidth(LHSExprType
);
11250 else if (LHSExprType
->isFixedPointType()) {
11251 auto FXSema
= S
.Context
.getFixedPointSemantics(LHSExprType
);
11252 LeftSize
= FXSema
.getWidth() - (unsigned)FXSema
.hasUnsignedPadding();
11254 if (Right
.uge(LeftSize
)) {
11255 S
.DiagRuntimeBehavior(Loc
, RHS
.get(),
11256 S
.PDiag(diag::warn_shift_gt_typewidth
)
11257 << RHS
.get()->getSourceRange());
11261 // FIXME: We probably need to handle fixed point types specially here.
11262 if (Opc
!= BO_Shl
|| LHSExprType
->isFixedPointType())
11265 // When left shifting an ICE which is signed, we can check for overflow which
11266 // according to C++ standards prior to C++2a has undefined behavior
11267 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11268 // more than the maximum value representable in the result type, so never
11269 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11270 // expression is still probably a bug.)
11271 Expr::EvalResult LHSResult
;
11272 if (LHS
.get()->isValueDependent() ||
11273 LHSType
->hasUnsignedIntegerRepresentation() ||
11274 !LHS
.get()->EvaluateAsInt(LHSResult
, S
.Context
))
11276 llvm::APSInt Left
= LHSResult
.Val
.getInt();
11278 // Don't warn if signed overflow is defined, then all the rest of the
11279 // diagnostics will not be triggered because the behavior is defined.
11280 // Also don't warn in C++20 mode (and newer), as signed left shifts
11281 // always wrap and never overflow.
11282 if (S
.getLangOpts().isSignedOverflowDefined() || S
.getLangOpts().CPlusPlus20
)
11285 // If LHS does not have a non-negative value then, the
11286 // behavior is undefined before C++2a. Warn about it.
11287 if (Left
.isNegative()) {
11288 S
.DiagRuntimeBehavior(Loc
, LHS
.get(),
11289 S
.PDiag(diag::warn_shift_lhs_negative
)
11290 << LHS
.get()->getSourceRange());
11294 llvm::APInt ResultBits
=
11295 static_cast<llvm::APInt
&>(Right
) + Left
.getSignificantBits();
11296 if (ResultBits
.ule(LeftSize
))
11298 llvm::APSInt Result
= Left
.extend(ResultBits
.getLimitedValue());
11299 Result
= Result
.shl(Right
);
11301 // Print the bit representation of the signed integer as an unsigned
11302 // hexadecimal number.
11303 SmallString
<40> HexResult
;
11304 Result
.toString(HexResult
, 16, /*Signed =*/false, /*Literal =*/true);
11306 // If we are only missing a sign bit, this is less likely to result in actual
11307 // bugs -- if the result is cast back to an unsigned type, it will have the
11308 // expected value. Thus we place this behind a different warning that can be
11309 // turned off separately if needed.
11310 if (ResultBits
- 1 == LeftSize
) {
11311 S
.Diag(Loc
, diag::warn_shift_result_sets_sign_bit
)
11312 << HexResult
<< LHSType
11313 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
11317 S
.Diag(Loc
, diag::warn_shift_result_gt_typewidth
)
11318 << HexResult
.str() << Result
.getSignificantBits() << LHSType
11319 << Left
.getBitWidth() << LHS
.get()->getSourceRange()
11320 << RHS
.get()->getSourceRange();
11323 /// Return the resulting type when a vector is shifted
11324 /// by a scalar or vector shift amount.
11325 static QualType
checkVectorShift(Sema
&S
, ExprResult
&LHS
, ExprResult
&RHS
,
11326 SourceLocation Loc
, bool IsCompAssign
) {
11327 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11328 if ((S
.LangOpts
.OpenCL
|| S
.LangOpts
.ZVector
) &&
11329 !LHS
.get()->getType()->isVectorType()) {
11330 S
.Diag(Loc
, diag::err_shift_rhs_only_vector
)
11331 << RHS
.get()->getType() << LHS
.get()->getType()
11332 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
11336 if (!IsCompAssign
) {
11337 LHS
= S
.UsualUnaryConversions(LHS
.get());
11338 if (LHS
.isInvalid()) return QualType();
11341 RHS
= S
.UsualUnaryConversions(RHS
.get());
11342 if (RHS
.isInvalid()) return QualType();
11344 QualType LHSType
= LHS
.get()->getType();
11345 // Note that LHS might be a scalar because the routine calls not only in
11347 const VectorType
*LHSVecTy
= LHSType
->getAs
<VectorType
>();
11348 QualType LHSEleType
= LHSVecTy
? LHSVecTy
->getElementType() : LHSType
;
11350 // Note that RHS might not be a vector.
11351 QualType RHSType
= RHS
.get()->getType();
11352 const VectorType
*RHSVecTy
= RHSType
->getAs
<VectorType
>();
11353 QualType RHSEleType
= RHSVecTy
? RHSVecTy
->getElementType() : RHSType
;
11355 // Do not allow shifts for boolean vectors.
11356 if ((LHSVecTy
&& LHSVecTy
->isExtVectorBoolType()) ||
11357 (RHSVecTy
&& RHSVecTy
->isExtVectorBoolType())) {
11358 S
.Diag(Loc
, diag::err_typecheck_invalid_operands
)
11359 << LHS
.get()->getType() << RHS
.get()->getType()
11360 << LHS
.get()->getSourceRange();
11364 // The operands need to be integers.
11365 if (!LHSEleType
->isIntegerType()) {
11366 S
.Diag(Loc
, diag::err_typecheck_expect_int
)
11367 << LHS
.get()->getType() << LHS
.get()->getSourceRange();
11371 if (!RHSEleType
->isIntegerType()) {
11372 S
.Diag(Loc
, diag::err_typecheck_expect_int
)
11373 << RHS
.get()->getType() << RHS
.get()->getSourceRange();
11381 if (LHSEleType
!= RHSEleType
) {
11382 LHS
= S
.ImpCastExprToType(LHS
.get(),RHSEleType
, CK_IntegralCast
);
11383 LHSEleType
= RHSEleType
;
11386 S
.Context
.getExtVectorType(LHSEleType
, RHSVecTy
->getNumElements());
11387 LHS
= S
.ImpCastExprToType(LHS
.get(), VecTy
, CK_VectorSplat
);
11389 } else if (RHSVecTy
) {
11390 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11391 // are applied component-wise. So if RHS is a vector, then ensure
11392 // that the number of elements is the same as LHS...
11393 if (RHSVecTy
->getNumElements() != LHSVecTy
->getNumElements()) {
11394 S
.Diag(Loc
, diag::err_typecheck_vector_lengths_not_equal
)
11395 << LHS
.get()->getType() << RHS
.get()->getType()
11396 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
11399 if (!S
.LangOpts
.OpenCL
&& !S
.LangOpts
.ZVector
) {
11400 const BuiltinType
*LHSBT
= LHSEleType
->getAs
<clang::BuiltinType
>();
11401 const BuiltinType
*RHSBT
= RHSEleType
->getAs
<clang::BuiltinType
>();
11402 if (LHSBT
!= RHSBT
&&
11403 S
.Context
.getTypeSize(LHSBT
) != S
.Context
.getTypeSize(RHSBT
)) {
11404 S
.Diag(Loc
, diag::warn_typecheck_vector_element_sizes_not_equal
)
11405 << LHS
.get()->getType() << RHS
.get()->getType()
11406 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
11410 // ...else expand RHS to match the number of elements in LHS.
11412 S
.Context
.getExtVectorType(RHSEleType
, LHSVecTy
->getNumElements());
11413 RHS
= S
.ImpCastExprToType(RHS
.get(), VecTy
, CK_VectorSplat
);
11419 static QualType
checkSizelessVectorShift(Sema
&S
, ExprResult
&LHS
,
11420 ExprResult
&RHS
, SourceLocation Loc
,
11421 bool IsCompAssign
) {
11422 if (!IsCompAssign
) {
11423 LHS
= S
.UsualUnaryConversions(LHS
.get());
11424 if (LHS
.isInvalid())
11428 RHS
= S
.UsualUnaryConversions(RHS
.get());
11429 if (RHS
.isInvalid())
11432 QualType LHSType
= LHS
.get()->getType();
11433 const BuiltinType
*LHSBuiltinTy
= LHSType
->castAs
<BuiltinType
>();
11434 QualType LHSEleType
= LHSType
->isSveVLSBuiltinType()
11435 ? LHSBuiltinTy
->getSveEltType(S
.getASTContext())
11438 // Note that RHS might not be a vector
11439 QualType RHSType
= RHS
.get()->getType();
11440 const BuiltinType
*RHSBuiltinTy
= RHSType
->castAs
<BuiltinType
>();
11441 QualType RHSEleType
= RHSType
->isSveVLSBuiltinType()
11442 ? RHSBuiltinTy
->getSveEltType(S
.getASTContext())
11445 if ((LHSBuiltinTy
&& LHSBuiltinTy
->isSVEBool()) ||
11446 (RHSBuiltinTy
&& RHSBuiltinTy
->isSVEBool())) {
11447 S
.Diag(Loc
, diag::err_typecheck_invalid_operands
)
11448 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange();
11452 if (!LHSEleType
->isIntegerType()) {
11453 S
.Diag(Loc
, diag::err_typecheck_expect_int
)
11454 << LHS
.get()->getType() << LHS
.get()->getSourceRange();
11458 if (!RHSEleType
->isIntegerType()) {
11459 S
.Diag(Loc
, diag::err_typecheck_expect_int
)
11460 << RHS
.get()->getType() << RHS
.get()->getSourceRange();
11464 if (LHSType
->isSveVLSBuiltinType() && RHSType
->isSveVLSBuiltinType() &&
11465 (S
.Context
.getBuiltinVectorTypeInfo(LHSBuiltinTy
).EC
!=
11466 S
.Context
.getBuiltinVectorTypeInfo(RHSBuiltinTy
).EC
)) {
11467 S
.Diag(Loc
, diag::err_typecheck_invalid_operands
)
11468 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
11469 << RHS
.get()->getSourceRange();
11473 if (!LHSType
->isSveVLSBuiltinType()) {
11474 assert(RHSType
->isSveVLSBuiltinType());
11477 if (LHSEleType
!= RHSEleType
) {
11478 LHS
= S
.ImpCastExprToType(LHS
.get(), RHSEleType
, clang::CK_IntegralCast
);
11479 LHSEleType
= RHSEleType
;
11481 const llvm::ElementCount VecSize
=
11482 S
.Context
.getBuiltinVectorTypeInfo(RHSBuiltinTy
).EC
;
11484 S
.Context
.getScalableVectorType(LHSEleType
, VecSize
.getKnownMinValue());
11485 LHS
= S
.ImpCastExprToType(LHS
.get(), VecTy
, clang::CK_VectorSplat
);
11487 } else if (RHSBuiltinTy
&& RHSBuiltinTy
->isSveVLSBuiltinType()) {
11488 if (S
.Context
.getTypeSize(RHSBuiltinTy
) !=
11489 S
.Context
.getTypeSize(LHSBuiltinTy
)) {
11490 S
.Diag(Loc
, diag::err_typecheck_vector_lengths_not_equal
)
11491 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
11492 << RHS
.get()->getSourceRange();
11496 const llvm::ElementCount VecSize
=
11497 S
.Context
.getBuiltinVectorTypeInfo(LHSBuiltinTy
).EC
;
11498 if (LHSEleType
!= RHSEleType
) {
11499 RHS
= S
.ImpCastExprToType(RHS
.get(), LHSEleType
, clang::CK_IntegralCast
);
11500 RHSEleType
= LHSEleType
;
11503 S
.Context
.getScalableVectorType(RHSEleType
, VecSize
.getKnownMinValue());
11504 RHS
= S
.ImpCastExprToType(RHS
.get(), VecTy
, CK_VectorSplat
);
11511 QualType
Sema::CheckShiftOperands(ExprResult
&LHS
, ExprResult
&RHS
,
11512 SourceLocation Loc
, BinaryOperatorKind Opc
,
11513 bool IsCompAssign
) {
11514 checkArithmeticNull(*this, LHS
, RHS
, Loc
, /*IsCompare=*/false);
11516 // Vector shifts promote their scalar inputs to vector type.
11517 if (LHS
.get()->getType()->isVectorType() ||
11518 RHS
.get()->getType()->isVectorType()) {
11519 if (LangOpts
.ZVector
) {
11520 // The shift operators for the z vector extensions work basically
11521 // like general shifts, except that neither the LHS nor the RHS is
11522 // allowed to be a "vector bool".
11523 if (auto LHSVecType
= LHS
.get()->getType()->getAs
<VectorType
>())
11524 if (LHSVecType
->getVectorKind() == VectorKind::AltiVecBool
)
11525 return InvalidOperands(Loc
, LHS
, RHS
);
11526 if (auto RHSVecType
= RHS
.get()->getType()->getAs
<VectorType
>())
11527 if (RHSVecType
->getVectorKind() == VectorKind::AltiVecBool
)
11528 return InvalidOperands(Loc
, LHS
, RHS
);
11530 return checkVectorShift(*this, LHS
, RHS
, Loc
, IsCompAssign
);
11533 if (LHS
.get()->getType()->isSveVLSBuiltinType() ||
11534 RHS
.get()->getType()->isSveVLSBuiltinType())
11535 return checkSizelessVectorShift(*this, LHS
, RHS
, Loc
, IsCompAssign
);
11537 // Shifts don't perform usual arithmetic conversions, they just do integer
11538 // promotions on each operand. C99 6.5.7p3
11540 // For the LHS, do usual unary conversions, but then reset them away
11541 // if this is a compound assignment.
11542 ExprResult OldLHS
= LHS
;
11543 LHS
= UsualUnaryConversions(LHS
.get());
11544 if (LHS
.isInvalid())
11546 QualType LHSType
= LHS
.get()->getType();
11547 if (IsCompAssign
) LHS
= OldLHS
;
11549 // The RHS is simpler.
11550 RHS
= UsualUnaryConversions(RHS
.get());
11551 if (RHS
.isInvalid())
11553 QualType RHSType
= RHS
.get()->getType();
11555 // C99 6.5.7p2: Each of the operands shall have integer type.
11556 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11557 if ((!LHSType
->isFixedPointOrIntegerType() &&
11558 !LHSType
->hasIntegerRepresentation()) ||
11559 !RHSType
->hasIntegerRepresentation())
11560 return InvalidOperands(Loc
, LHS
, RHS
);
11562 // C++0x: Don't allow scoped enums. FIXME: Use something better than
11563 // hasIntegerRepresentation() above instead of this.
11564 if (isScopedEnumerationType(LHSType
) ||
11565 isScopedEnumerationType(RHSType
)) {
11566 return InvalidOperands(Loc
, LHS
, RHS
);
11568 DiagnoseBadShiftValues(*this, LHS
, RHS
, Loc
, Opc
, LHSType
);
11570 // "The type of the result is that of the promoted left operand."
11574 /// Diagnose bad pointer comparisons.
11575 static void diagnoseDistinctPointerComparison(Sema
&S
, SourceLocation Loc
,
11576 ExprResult
&LHS
, ExprResult
&RHS
,
11578 S
.Diag(Loc
, IsError
? diag::err_typecheck_comparison_of_distinct_pointers
11579 : diag::ext_typecheck_comparison_of_distinct_pointers
)
11580 << LHS
.get()->getType() << RHS
.get()->getType()
11581 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
11584 /// Returns false if the pointers are converted to a composite type,
11585 /// true otherwise.
11586 static bool convertPointersToCompositeType(Sema
&S
, SourceLocation Loc
,
11587 ExprResult
&LHS
, ExprResult
&RHS
) {
11588 // C++ [expr.rel]p2:
11589 // [...] Pointer conversions (4.10) and qualification
11590 // conversions (4.4) are performed on pointer operands (or on
11591 // a pointer operand and a null pointer constant) to bring
11592 // them to their composite pointer type. [...]
11594 // C++ [expr.eq]p1 uses the same notion for (in)equality
11595 // comparisons of pointers.
11597 QualType LHSType
= LHS
.get()->getType();
11598 QualType RHSType
= RHS
.get()->getType();
11599 assert(LHSType
->isPointerType() || RHSType
->isPointerType() ||
11600 LHSType
->isMemberPointerType() || RHSType
->isMemberPointerType());
11602 QualType T
= S
.FindCompositePointerType(Loc
, LHS
, RHS
);
11604 if ((LHSType
->isAnyPointerType() || LHSType
->isMemberPointerType()) &&
11605 (RHSType
->isAnyPointerType() || RHSType
->isMemberPointerType()))
11606 diagnoseDistinctPointerComparison(S
, Loc
, LHS
, RHS
, /*isError*/true);
11608 S
.InvalidOperands(Loc
, LHS
, RHS
);
11615 static void diagnoseFunctionPointerToVoidComparison(Sema
&S
, SourceLocation Loc
,
11619 S
.Diag(Loc
, IsError
? diag::err_typecheck_comparison_of_fptr_to_void
11620 : diag::ext_typecheck_comparison_of_fptr_to_void
)
11621 << LHS
.get()->getType() << RHS
.get()->getType()
11622 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
11625 static bool isObjCObjectLiteral(ExprResult
&E
) {
11626 switch (E
.get()->IgnoreParenImpCasts()->getStmtClass()) {
11627 case Stmt::ObjCArrayLiteralClass
:
11628 case Stmt::ObjCDictionaryLiteralClass
:
11629 case Stmt::ObjCStringLiteralClass
:
11630 case Stmt::ObjCBoxedExprClass
:
11633 // Note that ObjCBoolLiteral is NOT an object literal!
11638 static bool hasIsEqualMethod(Sema
&S
, const Expr
*LHS
, const Expr
*RHS
) {
11639 const ObjCObjectPointerType
*Type
=
11640 LHS
->getType()->getAs
<ObjCObjectPointerType
>();
11642 // If this is not actually an Objective-C object, bail out.
11646 // Get the LHS object's interface type.
11647 QualType InterfaceType
= Type
->getPointeeType();
11649 // If the RHS isn't an Objective-C object, bail out.
11650 if (!RHS
->getType()->isObjCObjectPointerType())
11653 // Try to find the -isEqual: method.
11654 Selector IsEqualSel
= S
.ObjC().NSAPIObj
->getIsEqualSelector();
11655 ObjCMethodDecl
*Method
=
11656 S
.ObjC().LookupMethodInObjectType(IsEqualSel
, InterfaceType
,
11657 /*IsInstance=*/true);
11659 if (Type
->isObjCIdType()) {
11660 // For 'id', just check the global pool.
11662 S
.ObjC().LookupInstanceMethodInGlobalPool(IsEqualSel
, SourceRange(),
11663 /*receiverId=*/true);
11665 // Check protocols.
11666 Method
= S
.ObjC().LookupMethodInQualifiedType(IsEqualSel
, Type
,
11667 /*IsInstance=*/true);
11674 QualType T
= Method
->parameters()[0]->getType();
11675 if (!T
->isObjCObjectPointerType())
11678 QualType R
= Method
->getReturnType();
11679 if (!R
->isScalarType())
11685 static void diagnoseObjCLiteralComparison(Sema
&S
, SourceLocation Loc
,
11686 ExprResult
&LHS
, ExprResult
&RHS
,
11687 BinaryOperator::Opcode Opc
){
11690 if (isObjCObjectLiteral(LHS
)) {
11691 Literal
= LHS
.get();
11694 Literal
= RHS
.get();
11698 // Don't warn on comparisons against nil.
11699 Other
= Other
->IgnoreParenCasts();
11700 if (Other
->isNullPointerConstant(S
.getASTContext(),
11701 Expr::NPC_ValueDependentIsNotNull
))
11704 // This should be kept in sync with warn_objc_literal_comparison.
11705 // LK_String should always be after the other literals, since it has its own
11707 SemaObjC::ObjCLiteralKind LiteralKind
= S
.ObjC().CheckLiteralKind(Literal
);
11708 assert(LiteralKind
!= SemaObjC::LK_Block
);
11709 if (LiteralKind
== SemaObjC::LK_None
) {
11710 llvm_unreachable("Unknown Objective-C object literal kind");
11713 if (LiteralKind
== SemaObjC::LK_String
)
11714 S
.Diag(Loc
, diag::warn_objc_string_literal_comparison
)
11715 << Literal
->getSourceRange();
11717 S
.Diag(Loc
, diag::warn_objc_literal_comparison
)
11718 << LiteralKind
<< Literal
->getSourceRange();
11720 if (BinaryOperator::isEqualityOp(Opc
) &&
11721 hasIsEqualMethod(S
, LHS
.get(), RHS
.get())) {
11722 SourceLocation Start
= LHS
.get()->getBeginLoc();
11723 SourceLocation End
= S
.getLocForEndOfToken(RHS
.get()->getEndLoc());
11724 CharSourceRange OpRange
=
11725 CharSourceRange::getCharRange(Loc
, S
.getLocForEndOfToken(Loc
));
11727 S
.Diag(Loc
, diag::note_objc_literal_comparison_isequal
)
11728 << FixItHint::CreateInsertion(Start
, Opc
== BO_EQ
? "[" : "![")
11729 << FixItHint::CreateReplacement(OpRange
, " isEqual:")
11730 << FixItHint::CreateInsertion(End
, "]");
11734 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11735 static void diagnoseLogicalNotOnLHSofCheck(Sema
&S
, ExprResult
&LHS
,
11736 ExprResult
&RHS
, SourceLocation Loc
,
11737 BinaryOperatorKind Opc
) {
11738 // Check that left hand side is !something.
11739 UnaryOperator
*UO
= dyn_cast
<UnaryOperator
>(LHS
.get()->IgnoreImpCasts());
11740 if (!UO
|| UO
->getOpcode() != UO_LNot
) return;
11742 // Only check if the right hand side is non-bool arithmetic type.
11743 if (RHS
.get()->isKnownToHaveBooleanValue()) return;
11745 // Make sure that the something in !something is not bool.
11746 Expr
*SubExpr
= UO
->getSubExpr()->IgnoreImpCasts();
11747 if (SubExpr
->isKnownToHaveBooleanValue()) return;
11750 bool IsBitwiseOp
= Opc
== BO_And
|| Opc
== BO_Or
|| Opc
== BO_Xor
;
11751 S
.Diag(UO
->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check
)
11752 << Loc
<< IsBitwiseOp
;
11754 // First note suggest !(x < y)
11755 SourceLocation FirstOpen
= SubExpr
->getBeginLoc();
11756 SourceLocation FirstClose
= RHS
.get()->getEndLoc();
11757 FirstClose
= S
.getLocForEndOfToken(FirstClose
);
11758 if (FirstClose
.isInvalid())
11759 FirstOpen
= SourceLocation();
11760 S
.Diag(UO
->getOperatorLoc(), diag::note_logical_not_fix
)
11762 << FixItHint::CreateInsertion(FirstOpen
, "(")
11763 << FixItHint::CreateInsertion(FirstClose
, ")");
11765 // Second note suggests (!x) < y
11766 SourceLocation SecondOpen
= LHS
.get()->getBeginLoc();
11767 SourceLocation SecondClose
= LHS
.get()->getEndLoc();
11768 SecondClose
= S
.getLocForEndOfToken(SecondClose
);
11769 if (SecondClose
.isInvalid())
11770 SecondOpen
= SourceLocation();
11771 S
.Diag(UO
->getOperatorLoc(), diag::note_logical_not_silence_with_parens
)
11772 << FixItHint::CreateInsertion(SecondOpen
, "(")
11773 << FixItHint::CreateInsertion(SecondClose
, ")");
11776 // Returns true if E refers to a non-weak array.
11777 static bool checkForArray(const Expr
*E
) {
11778 const ValueDecl
*D
= nullptr;
11779 if (const DeclRefExpr
*DR
= dyn_cast
<DeclRefExpr
>(E
)) {
11781 } else if (const MemberExpr
*Mem
= dyn_cast
<MemberExpr
>(E
)) {
11782 if (Mem
->isImplicitAccess())
11783 D
= Mem
->getMemberDecl();
11787 return D
->getType()->isArrayType() && !D
->isWeak();
11790 /// Diagnose some forms of syntactically-obvious tautological comparison.
11791 static void diagnoseTautologicalComparison(Sema
&S
, SourceLocation Loc
,
11792 Expr
*LHS
, Expr
*RHS
,
11793 BinaryOperatorKind Opc
) {
11794 Expr
*LHSStripped
= LHS
->IgnoreParenImpCasts();
11795 Expr
*RHSStripped
= RHS
->IgnoreParenImpCasts();
11797 QualType LHSType
= LHS
->getType();
11798 QualType RHSType
= RHS
->getType();
11799 if (LHSType
->hasFloatingRepresentation() ||
11800 (LHSType
->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc
)) ||
11801 S
.inTemplateInstantiation())
11804 // WebAssembly Tables cannot be compared, therefore shouldn't emit
11805 // Tautological diagnostics.
11806 if (LHSType
->isWebAssemblyTableType() || RHSType
->isWebAssemblyTableType())
11809 // Comparisons between two array types are ill-formed for operator<=>, so
11810 // we shouldn't emit any additional warnings about it.
11811 if (Opc
== BO_Cmp
&& LHSType
->isArrayType() && RHSType
->isArrayType())
11814 // For non-floating point types, check for self-comparisons of the form
11815 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
11816 // often indicate logic errors in the program.
11818 // NOTE: Don't warn about comparison expressions resulting from macro
11819 // expansion. Also don't warn about comparisons which are only self
11820 // comparisons within a template instantiation. The warnings should catch
11821 // obvious cases in the definition of the template anyways. The idea is to
11822 // warn when the typed comparison operator will always evaluate to the same
11825 // Used for indexing into %select in warn_comparison_always
11830 AlwaysEqual
, // std::strong_ordering::equal from operator<=>
11833 // C++2a [depr.array.comp]:
11834 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11835 // operands of array type are deprecated.
11836 if (S
.getLangOpts().CPlusPlus20
&& LHSStripped
->getType()->isArrayType() &&
11837 RHSStripped
->getType()->isArrayType()) {
11838 S
.Diag(Loc
, diag::warn_depr_array_comparison
)
11839 << LHS
->getSourceRange() << RHS
->getSourceRange()
11840 << LHSStripped
->getType() << RHSStripped
->getType();
11841 // Carry on to produce the tautological comparison warning, if this
11842 // expression is potentially-evaluated, we can resolve the array to a
11843 // non-weak declaration, and so on.
11846 if (!LHS
->getBeginLoc().isMacroID() && !RHS
->getBeginLoc().isMacroID()) {
11847 if (Expr::isSameComparisonOperand(LHS
, RHS
)) {
11853 Result
= AlwaysTrue
;
11858 Result
= AlwaysFalse
;
11861 Result
= AlwaysEqual
;
11864 Result
= AlwaysConstant
;
11867 S
.DiagRuntimeBehavior(Loc
, nullptr,
11868 S
.PDiag(diag::warn_comparison_always
)
11869 << 0 /*self-comparison*/
11871 } else if (checkForArray(LHSStripped
) && checkForArray(RHSStripped
)) {
11872 // What is it always going to evaluate to?
11875 case BO_EQ
: // e.g. array1 == array2
11876 Result
= AlwaysFalse
;
11878 case BO_NE
: // e.g. array1 != array2
11879 Result
= AlwaysTrue
;
11881 default: // e.g. array1 <= array2
11882 // The best we can say is 'a constant'
11883 Result
= AlwaysConstant
;
11886 S
.DiagRuntimeBehavior(Loc
, nullptr,
11887 S
.PDiag(diag::warn_comparison_always
)
11888 << 1 /*array comparison*/
11893 if (isa
<CastExpr
>(LHSStripped
))
11894 LHSStripped
= LHSStripped
->IgnoreParenCasts();
11895 if (isa
<CastExpr
>(RHSStripped
))
11896 RHSStripped
= RHSStripped
->IgnoreParenCasts();
11898 // Warn about comparisons against a string constant (unless the other
11899 // operand is null); the user probably wants string comparison function.
11900 Expr
*LiteralString
= nullptr;
11901 Expr
*LiteralStringStripped
= nullptr;
11902 if ((isa
<StringLiteral
>(LHSStripped
) || isa
<ObjCEncodeExpr
>(LHSStripped
)) &&
11903 !RHSStripped
->isNullPointerConstant(S
.Context
,
11904 Expr::NPC_ValueDependentIsNull
)) {
11905 LiteralString
= LHS
;
11906 LiteralStringStripped
= LHSStripped
;
11907 } else if ((isa
<StringLiteral
>(RHSStripped
) ||
11908 isa
<ObjCEncodeExpr
>(RHSStripped
)) &&
11909 !LHSStripped
->isNullPointerConstant(S
.Context
,
11910 Expr::NPC_ValueDependentIsNull
)) {
11911 LiteralString
= RHS
;
11912 LiteralStringStripped
= RHSStripped
;
11915 if (LiteralString
) {
11916 S
.DiagRuntimeBehavior(Loc
, nullptr,
11917 S
.PDiag(diag::warn_stringcompare
)
11918 << isa
<ObjCEncodeExpr
>(LiteralStringStripped
)
11919 << LiteralString
->getSourceRange());
11923 static ImplicitConversionKind
castKindToImplicitConversionKind(CastKind CK
) {
11927 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK
)
11930 llvm_unreachable("unhandled cast kind");
11932 case CK_UserDefinedConversion
:
11933 return ICK_Identity
;
11934 case CK_LValueToRValue
:
11935 return ICK_Lvalue_To_Rvalue
;
11936 case CK_ArrayToPointerDecay
:
11937 return ICK_Array_To_Pointer
;
11938 case CK_FunctionToPointerDecay
:
11939 return ICK_Function_To_Pointer
;
11940 case CK_IntegralCast
:
11941 return ICK_Integral_Conversion
;
11942 case CK_FloatingCast
:
11943 return ICK_Floating_Conversion
;
11944 case CK_IntegralToFloating
:
11945 case CK_FloatingToIntegral
:
11946 return ICK_Floating_Integral
;
11947 case CK_IntegralComplexCast
:
11948 case CK_FloatingComplexCast
:
11949 case CK_FloatingComplexToIntegralComplex
:
11950 case CK_IntegralComplexToFloatingComplex
:
11951 return ICK_Complex_Conversion
;
11952 case CK_FloatingComplexToReal
:
11953 case CK_FloatingRealToComplex
:
11954 case CK_IntegralComplexToReal
:
11955 case CK_IntegralRealToComplex
:
11956 return ICK_Complex_Real
;
11957 case CK_HLSLArrayRValue
:
11958 return ICK_HLSL_Array_RValue
;
11962 static bool checkThreeWayNarrowingConversion(Sema
&S
, QualType ToType
, Expr
*E
,
11964 SourceLocation Loc
) {
11965 // Check for a narrowing implicit conversion.
11966 StandardConversionSequence SCS
;
11967 SCS
.setAsIdentityConversion();
11968 SCS
.setToType(0, FromType
);
11969 SCS
.setToType(1, ToType
);
11970 if (const auto *ICE
= dyn_cast
<ImplicitCastExpr
>(E
))
11971 SCS
.Second
= castKindToImplicitConversionKind(ICE
->getCastKind());
11973 APValue PreNarrowingValue
;
11974 QualType PreNarrowingType
;
11975 switch (SCS
.getNarrowingKind(S
.Context
, E
, PreNarrowingValue
,
11977 /*IgnoreFloatToIntegralConversion*/ true)) {
11978 case NK_Dependent_Narrowing
:
11979 // Implicit conversion to a narrower type, but the expression is
11980 // value-dependent so we can't tell whether it's actually narrowing.
11981 case NK_Not_Narrowing
:
11984 case NK_Constant_Narrowing
:
11985 // Implicit conversion to a narrower type, and the value is not a constant
11987 S
.Diag(E
->getBeginLoc(), diag::err_spaceship_argument_narrowing
)
11989 << PreNarrowingValue
.getAsString(S
.Context
, PreNarrowingType
) << ToType
;
11992 case NK_Variable_Narrowing
:
11993 // Implicit conversion to a narrower type, and the value is not a constant
11995 case NK_Type_Narrowing
:
11996 S
.Diag(E
->getBeginLoc(), diag::err_spaceship_argument_narrowing
)
11997 << /*Constant*/ 0 << FromType
<< ToType
;
11998 // TODO: It's not a constant expression, but what if the user intended it
11999 // to be? Can we produce notes to help them figure out why it isn't?
12002 llvm_unreachable("unhandled case in switch");
12005 static QualType
checkArithmeticOrEnumeralThreeWayCompare(Sema
&S
,
12008 SourceLocation Loc
) {
12009 QualType LHSType
= LHS
.get()->getType();
12010 QualType RHSType
= RHS
.get()->getType();
12011 // Dig out the original argument type and expression before implicit casts
12012 // were applied. These are the types/expressions we need to check the
12013 // [expr.spaceship] requirements against.
12014 ExprResult LHSStripped
= LHS
.get()->IgnoreParenImpCasts();
12015 ExprResult RHSStripped
= RHS
.get()->IgnoreParenImpCasts();
12016 QualType LHSStrippedType
= LHSStripped
.get()->getType();
12017 QualType RHSStrippedType
= RHSStripped
.get()->getType();
12019 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12020 // other is not, the program is ill-formed.
12021 if (LHSStrippedType
->isBooleanType() != RHSStrippedType
->isBooleanType()) {
12022 S
.InvalidOperands(Loc
, LHSStripped
, RHSStripped
);
12026 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12027 int NumEnumArgs
= (int)LHSStrippedType
->isEnumeralType() +
12028 RHSStrippedType
->isEnumeralType();
12029 if (NumEnumArgs
== 1) {
12030 bool LHSIsEnum
= LHSStrippedType
->isEnumeralType();
12031 QualType OtherTy
= LHSIsEnum
? RHSStrippedType
: LHSStrippedType
;
12032 if (OtherTy
->hasFloatingRepresentation()) {
12033 S
.InvalidOperands(Loc
, LHSStripped
, RHSStripped
);
12037 if (NumEnumArgs
== 2) {
12038 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12039 // type E, the operator yields the result of converting the operands
12040 // to the underlying type of E and applying <=> to the converted operands.
12041 if (!S
.Context
.hasSameUnqualifiedType(LHSStrippedType
, RHSStrippedType
)) {
12042 S
.InvalidOperands(Loc
, LHS
, RHS
);
12046 LHSStrippedType
->castAs
<EnumType
>()->getDecl()->getIntegerType();
12047 assert(IntType
->isArithmeticType());
12049 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12050 // promote the boolean type, and all other promotable integer types, to
12052 if (S
.Context
.isPromotableIntegerType(IntType
))
12053 IntType
= S
.Context
.getPromotedIntegerType(IntType
);
12055 LHS
= S
.ImpCastExprToType(LHS
.get(), IntType
, CK_IntegralCast
);
12056 RHS
= S
.ImpCastExprToType(RHS
.get(), IntType
, CK_IntegralCast
);
12057 LHSType
= RHSType
= IntType
;
12060 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12061 // usual arithmetic conversions are applied to the operands.
12063 S
.UsualArithmeticConversions(LHS
, RHS
, Loc
, Sema::ACK_Comparison
);
12064 if (LHS
.isInvalid() || RHS
.isInvalid())
12067 return S
.InvalidOperands(Loc
, LHS
, RHS
);
12069 std::optional
<ComparisonCategoryType
> CCT
=
12070 getComparisonCategoryForBuiltinCmp(Type
);
12072 return S
.InvalidOperands(Loc
, LHS
, RHS
);
12074 bool HasNarrowing
= checkThreeWayNarrowingConversion(
12075 S
, Type
, LHS
.get(), LHSType
, LHS
.get()->getBeginLoc());
12076 HasNarrowing
|= checkThreeWayNarrowingConversion(S
, Type
, RHS
.get(), RHSType
,
12077 RHS
.get()->getBeginLoc());
12081 assert(!Type
.isNull() && "composite type for <=> has not been set");
12083 return S
.CheckComparisonCategoryType(
12084 *CCT
, Loc
, Sema::ComparisonCategoryUsage::OperatorInExpression
);
12087 static QualType
checkArithmeticOrEnumeralCompare(Sema
&S
, ExprResult
&LHS
,
12089 SourceLocation Loc
,
12090 BinaryOperatorKind Opc
) {
12092 return checkArithmeticOrEnumeralThreeWayCompare(S
, LHS
, RHS
, Loc
);
12094 // C99 6.5.8p3 / C99 6.5.9p4
12096 S
.UsualArithmeticConversions(LHS
, RHS
, Loc
, Sema::ACK_Comparison
);
12097 if (LHS
.isInvalid() || RHS
.isInvalid())
12100 return S
.InvalidOperands(Loc
, LHS
, RHS
);
12101 assert(Type
->isArithmeticType() || Type
->isEnumeralType());
12103 if (Type
->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc
))
12104 return S
.InvalidOperands(Loc
, LHS
, RHS
);
12106 // Check for comparisons of floating point operands using != and ==.
12107 if (Type
->hasFloatingRepresentation())
12108 S
.CheckFloatComparison(Loc
, LHS
.get(), RHS
.get(), Opc
);
12110 // The result of comparisons is 'bool' in C++, 'int' in C.
12111 return S
.Context
.getLogicalOperationType();
12114 void Sema::CheckPtrComparisonWithNullChar(ExprResult
&E
, ExprResult
&NullE
) {
12115 if (!NullE
.get()->getType()->isAnyPointerType())
12117 int NullValue
= PP
.isMacroDefined("NULL") ? 0 : 1;
12118 if (!E
.get()->getType()->isAnyPointerType() &&
12119 E
.get()->isNullPointerConstant(Context
,
12120 Expr::NPC_ValueDependentIsNotNull
) ==
12121 Expr::NPCK_ZeroExpression
) {
12122 if (const auto *CL
= dyn_cast
<CharacterLiteral
>(E
.get())) {
12123 if (CL
->getValue() == 0)
12124 Diag(E
.get()->getExprLoc(), diag::warn_pointer_compare
)
12126 << FixItHint::CreateReplacement(E
.get()->getExprLoc(),
12127 NullValue
? "NULL" : "(void *)0");
12128 } else if (const auto *CE
= dyn_cast
<CStyleCastExpr
>(E
.get())) {
12129 TypeSourceInfo
*TI
= CE
->getTypeInfoAsWritten();
12130 QualType T
= Context
.getCanonicalType(TI
->getType()).getUnqualifiedType();
12131 if (T
== Context
.CharTy
)
12132 Diag(E
.get()->getExprLoc(), diag::warn_pointer_compare
)
12134 << FixItHint::CreateReplacement(E
.get()->getExprLoc(),
12135 NullValue
? "NULL" : "(void *)0");
12140 // C99 6.5.8, C++ [expr.rel]
12141 QualType
Sema::CheckCompareOperands(ExprResult
&LHS
, ExprResult
&RHS
,
12142 SourceLocation Loc
,
12143 BinaryOperatorKind Opc
) {
12144 bool IsRelational
= BinaryOperator::isRelationalOp(Opc
);
12145 bool IsThreeWay
= Opc
== BO_Cmp
;
12146 bool IsOrdered
= IsRelational
|| IsThreeWay
;
12147 auto IsAnyPointerType
= [](ExprResult E
) {
12148 QualType Ty
= E
.get()->getType();
12149 return Ty
->isPointerType() || Ty
->isMemberPointerType();
12152 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12153 // type, array-to-pointer, ..., conversions are performed on both operands to
12154 // bring them to their composite type.
12155 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12156 // any type-related checks.
12157 if (!IsThreeWay
|| IsAnyPointerType(LHS
) || IsAnyPointerType(RHS
)) {
12158 LHS
= DefaultFunctionArrayLvalueConversion(LHS
.get());
12159 if (LHS
.isInvalid())
12161 RHS
= DefaultFunctionArrayLvalueConversion(RHS
.get());
12162 if (RHS
.isInvalid())
12165 LHS
= DefaultLvalueConversion(LHS
.get());
12166 if (LHS
.isInvalid())
12168 RHS
= DefaultLvalueConversion(RHS
.get());
12169 if (RHS
.isInvalid())
12173 checkArithmeticNull(*this, LHS
, RHS
, Loc
, /*IsCompare=*/true);
12174 if (!getLangOpts().CPlusPlus
&& BinaryOperator::isEqualityOp(Opc
)) {
12175 CheckPtrComparisonWithNullChar(LHS
, RHS
);
12176 CheckPtrComparisonWithNullChar(RHS
, LHS
);
12179 // Handle vector comparisons separately.
12180 if (LHS
.get()->getType()->isVectorType() ||
12181 RHS
.get()->getType()->isVectorType())
12182 return CheckVectorCompareOperands(LHS
, RHS
, Loc
, Opc
);
12184 if (LHS
.get()->getType()->isSveVLSBuiltinType() ||
12185 RHS
.get()->getType()->isSveVLSBuiltinType())
12186 return CheckSizelessVectorCompareOperands(LHS
, RHS
, Loc
, Opc
);
12188 diagnoseLogicalNotOnLHSofCheck(*this, LHS
, RHS
, Loc
, Opc
);
12189 diagnoseTautologicalComparison(*this, Loc
, LHS
.get(), RHS
.get(), Opc
);
12191 QualType LHSType
= LHS
.get()->getType();
12192 QualType RHSType
= RHS
.get()->getType();
12193 if ((LHSType
->isArithmeticType() || LHSType
->isEnumeralType()) &&
12194 (RHSType
->isArithmeticType() || RHSType
->isEnumeralType()))
12195 return checkArithmeticOrEnumeralCompare(*this, LHS
, RHS
, Loc
, Opc
);
12197 if ((LHSType
->isPointerType() &&
12198 LHSType
->getPointeeType().isWebAssemblyReferenceType()) ||
12199 (RHSType
->isPointerType() &&
12200 RHSType
->getPointeeType().isWebAssemblyReferenceType()))
12201 return InvalidOperands(Loc
, LHS
, RHS
);
12203 const Expr::NullPointerConstantKind LHSNullKind
=
12204 LHS
.get()->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull
);
12205 const Expr::NullPointerConstantKind RHSNullKind
=
12206 RHS
.get()->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull
);
12207 bool LHSIsNull
= LHSNullKind
!= Expr::NPCK_NotNull
;
12208 bool RHSIsNull
= RHSNullKind
!= Expr::NPCK_NotNull
;
12210 auto computeResultTy
= [&]() {
12212 return Context
.getLogicalOperationType();
12213 assert(getLangOpts().CPlusPlus
);
12214 assert(Context
.hasSameType(LHS
.get()->getType(), RHS
.get()->getType()));
12216 QualType CompositeTy
= LHS
.get()->getType();
12217 assert(!CompositeTy
->isReferenceType());
12219 std::optional
<ComparisonCategoryType
> CCT
=
12220 getComparisonCategoryForBuiltinCmp(CompositeTy
);
12222 return InvalidOperands(Loc
, LHS
, RHS
);
12224 if (CompositeTy
->isPointerType() && LHSIsNull
!= RHSIsNull
) {
12225 // P0946R0: Comparisons between a null pointer constant and an object
12226 // pointer result in std::strong_equality, which is ill-formed under
12228 Diag(Loc
, diag::err_typecheck_three_way_comparison_of_pointer_and_zero
)
12229 << (LHSIsNull
? LHS
.get()->getSourceRange()
12230 : RHS
.get()->getSourceRange());
12234 return CheckComparisonCategoryType(
12235 *CCT
, Loc
, ComparisonCategoryUsage::OperatorInExpression
);
12238 if (!IsOrdered
&& LHSIsNull
!= RHSIsNull
) {
12239 bool IsEquality
= Opc
== BO_EQ
;
12241 DiagnoseAlwaysNonNullPointer(LHS
.get(), RHSNullKind
, IsEquality
,
12242 RHS
.get()->getSourceRange());
12244 DiagnoseAlwaysNonNullPointer(RHS
.get(), LHSNullKind
, IsEquality
,
12245 LHS
.get()->getSourceRange());
12248 if (IsOrdered
&& LHSType
->isFunctionPointerType() &&
12249 RHSType
->isFunctionPointerType()) {
12250 // Valid unless a relational comparison of function pointers
12251 bool IsError
= Opc
== BO_Cmp
;
12253 IsError
? diag::err_typecheck_ordered_comparison_of_function_pointers
12254 : getLangOpts().CPlusPlus
12255 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12256 : diag::ext_typecheck_ordered_comparison_of_function_pointers
;
12257 Diag(Loc
, DiagID
) << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
12258 << RHS
.get()->getSourceRange();
12263 if ((LHSType
->isIntegerType() && !LHSIsNull
) ||
12264 (RHSType
->isIntegerType() && !RHSIsNull
)) {
12265 // Skip normal pointer conversion checks in this case; we have better
12266 // diagnostics for this below.
12267 } else if (getLangOpts().CPlusPlus
) {
12268 // Equality comparison of a function pointer to a void pointer is invalid,
12269 // but we allow it as an extension.
12270 // FIXME: If we really want to allow this, should it be part of composite
12271 // pointer type computation so it works in conditionals too?
12273 ((LHSType
->isFunctionPointerType() && RHSType
->isVoidPointerType()) ||
12274 (RHSType
->isFunctionPointerType() && LHSType
->isVoidPointerType()))) {
12275 // This is a gcc extension compatibility comparison.
12276 // In a SFINAE context, we treat this as a hard error to maintain
12277 // conformance with the C++ standard.
12278 diagnoseFunctionPointerToVoidComparison(
12279 *this, Loc
, LHS
, RHS
, /*isError*/ (bool)isSFINAEContext());
12281 if (isSFINAEContext())
12284 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_BitCast
);
12285 return computeResultTy();
12288 // C++ [expr.eq]p2:
12289 // If at least one operand is a pointer [...] bring them to their
12290 // composite pointer type.
12291 // C++ [expr.spaceship]p6
12292 // If at least one of the operands is of pointer type, [...] bring them
12293 // to their composite pointer type.
12294 // C++ [expr.rel]p2:
12295 // If both operands are pointers, [...] bring them to their composite
12297 // For <=>, the only valid non-pointer types are arrays and functions, and
12298 // we already decayed those, so this is really the same as the relational
12299 // comparison rule.
12300 if ((int)LHSType
->isPointerType() + (int)RHSType
->isPointerType() >=
12301 (IsOrdered
? 2 : 1) &&
12302 (!LangOpts
.ObjCAutoRefCount
|| !(LHSType
->isObjCObjectPointerType() ||
12303 RHSType
->isObjCObjectPointerType()))) {
12304 if (convertPointersToCompositeType(*this, Loc
, LHS
, RHS
))
12306 return computeResultTy();
12308 } else if (LHSType
->isPointerType() &&
12309 RHSType
->isPointerType()) { // C99 6.5.8p2
12310 // All of the following pointer-related warnings are GCC extensions, except
12311 // when handling null pointer constants.
12312 QualType LCanPointeeTy
=
12313 LHSType
->castAs
<PointerType
>()->getPointeeType().getCanonicalType();
12314 QualType RCanPointeeTy
=
12315 RHSType
->castAs
<PointerType
>()->getPointeeType().getCanonicalType();
12317 // C99 6.5.9p2 and C99 6.5.8p2
12318 if (Context
.typesAreCompatible(LCanPointeeTy
.getUnqualifiedType(),
12319 RCanPointeeTy
.getUnqualifiedType())) {
12320 if (IsRelational
) {
12321 // Pointers both need to point to complete or incomplete types
12322 if ((LCanPointeeTy
->isIncompleteType() !=
12323 RCanPointeeTy
->isIncompleteType()) &&
12324 !getLangOpts().C11
) {
12325 Diag(Loc
, diag::ext_typecheck_compare_complete_incomplete_pointers
)
12326 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange()
12327 << LHSType
<< RHSType
<< LCanPointeeTy
->isIncompleteType()
12328 << RCanPointeeTy
->isIncompleteType();
12331 } else if (!IsRelational
&&
12332 (LCanPointeeTy
->isVoidType() || RCanPointeeTy
->isVoidType())) {
12333 // Valid unless comparison between non-null pointer and function pointer
12334 if ((LCanPointeeTy
->isFunctionType() || RCanPointeeTy
->isFunctionType())
12335 && !LHSIsNull
&& !RHSIsNull
)
12336 diagnoseFunctionPointerToVoidComparison(*this, Loc
, LHS
, RHS
,
12340 diagnoseDistinctPointerComparison(*this, Loc
, LHS
, RHS
, /*isError*/false);
12342 if (LCanPointeeTy
!= RCanPointeeTy
) {
12343 // Treat NULL constant as a special case in OpenCL.
12344 if (getLangOpts().OpenCL
&& !LHSIsNull
&& !RHSIsNull
) {
12345 if (!LCanPointeeTy
.isAddressSpaceOverlapping(RCanPointeeTy
,
12346 getASTContext())) {
12348 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers
)
12349 << LHSType
<< RHSType
<< 0 /* comparison */
12350 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
12353 LangAS AddrSpaceL
= LCanPointeeTy
.getAddressSpace();
12354 LangAS AddrSpaceR
= RCanPointeeTy
.getAddressSpace();
12355 CastKind Kind
= AddrSpaceL
!= AddrSpaceR
? CK_AddressSpaceConversion
12357 if (LHSIsNull
&& !RHSIsNull
)
12358 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, Kind
);
12360 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, Kind
);
12362 return computeResultTy();
12366 // C++ [expr.eq]p4:
12367 // Two operands of type std::nullptr_t or one operand of type
12368 // std::nullptr_t and the other a null pointer constant compare
12371 // If both operands have type nullptr_t or one operand has type nullptr_t
12372 // and the other is a null pointer constant, they compare equal if the
12373 // former is a null pointer.
12374 if (!IsOrdered
&& LHSIsNull
&& RHSIsNull
) {
12375 if (LHSType
->isNullPtrType()) {
12376 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_NullToPointer
);
12377 return computeResultTy();
12379 if (RHSType
->isNullPtrType()) {
12380 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_NullToPointer
);
12381 return computeResultTy();
12385 if (!getLangOpts().CPlusPlus
&& !IsOrdered
&& (LHSIsNull
|| RHSIsNull
)) {
12387 // Otherwise, at least one operand is a pointer. If one is a pointer and
12388 // the other is a null pointer constant or has type nullptr_t, they
12390 if (LHSIsNull
&& RHSType
->isPointerType()) {
12391 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_NullToPointer
);
12392 return computeResultTy();
12394 if (RHSIsNull
&& LHSType
->isPointerType()) {
12395 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_NullToPointer
);
12396 return computeResultTy();
12400 // Comparison of Objective-C pointers and block pointers against nullptr_t.
12401 // These aren't covered by the composite pointer type rules.
12402 if (!IsOrdered
&& RHSType
->isNullPtrType() &&
12403 (LHSType
->isObjCObjectPointerType() || LHSType
->isBlockPointerType())) {
12404 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_NullToPointer
);
12405 return computeResultTy();
12407 if (!IsOrdered
&& LHSType
->isNullPtrType() &&
12408 (RHSType
->isObjCObjectPointerType() || RHSType
->isBlockPointerType())) {
12409 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_NullToPointer
);
12410 return computeResultTy();
12413 if (getLangOpts().CPlusPlus
) {
12414 if (IsRelational
&&
12415 ((LHSType
->isNullPtrType() && RHSType
->isPointerType()) ||
12416 (RHSType
->isNullPtrType() && LHSType
->isPointerType()))) {
12417 // HACK: Relational comparison of nullptr_t against a pointer type is
12418 // invalid per DR583, but we allow it within std::less<> and friends,
12419 // since otherwise common uses of it break.
12420 // FIXME: Consider removing this hack once LWG fixes std::less<> and
12421 // friends to have std::nullptr_t overload candidates.
12422 DeclContext
*DC
= CurContext
;
12423 if (isa
<FunctionDecl
>(DC
))
12424 DC
= DC
->getParent();
12425 if (auto *CTSD
= dyn_cast
<ClassTemplateSpecializationDecl
>(DC
)) {
12426 if (CTSD
->isInStdNamespace() &&
12427 llvm::StringSwitch
<bool>(CTSD
->getName())
12428 .Cases("less", "less_equal", "greater", "greater_equal", true)
12430 if (RHSType
->isNullPtrType())
12431 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_NullToPointer
);
12433 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_NullToPointer
);
12434 return computeResultTy();
12439 // C++ [expr.eq]p2:
12440 // If at least one operand is a pointer to member, [...] bring them to
12441 // their composite pointer type.
12443 (LHSType
->isMemberPointerType() || RHSType
->isMemberPointerType())) {
12444 if (convertPointersToCompositeType(*this, Loc
, LHS
, RHS
))
12447 return computeResultTy();
12451 // Handle block pointer types.
12452 if (!IsOrdered
&& LHSType
->isBlockPointerType() &&
12453 RHSType
->isBlockPointerType()) {
12454 QualType lpointee
= LHSType
->castAs
<BlockPointerType
>()->getPointeeType();
12455 QualType rpointee
= RHSType
->castAs
<BlockPointerType
>()->getPointeeType();
12457 if (!LHSIsNull
&& !RHSIsNull
&&
12458 !Context
.typesAreCompatible(lpointee
, rpointee
)) {
12459 Diag(Loc
, diag::err_typecheck_comparison_of_distinct_blocks
)
12460 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
12461 << RHS
.get()->getSourceRange();
12463 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_BitCast
);
12464 return computeResultTy();
12467 // Allow block pointers to be compared with null pointer constants.
12469 && ((LHSType
->isBlockPointerType() && RHSType
->isPointerType())
12470 || (LHSType
->isPointerType() && RHSType
->isBlockPointerType()))) {
12471 if (!LHSIsNull
&& !RHSIsNull
) {
12472 if (!((RHSType
->isPointerType() && RHSType
->castAs
<PointerType
>()
12473 ->getPointeeType()->isVoidType())
12474 || (LHSType
->isPointerType() && LHSType
->castAs
<PointerType
>()
12475 ->getPointeeType()->isVoidType())))
12476 Diag(Loc
, diag::err_typecheck_comparison_of_distinct_blocks
)
12477 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
12478 << RHS
.get()->getSourceRange();
12480 if (LHSIsNull
&& !RHSIsNull
)
12481 LHS
= ImpCastExprToType(LHS
.get(), RHSType
,
12482 RHSType
->isPointerType() ? CK_BitCast
12483 : CK_AnyPointerToBlockPointerCast
);
12485 RHS
= ImpCastExprToType(RHS
.get(), LHSType
,
12486 LHSType
->isPointerType() ? CK_BitCast
12487 : CK_AnyPointerToBlockPointerCast
);
12488 return computeResultTy();
12491 if (LHSType
->isObjCObjectPointerType() ||
12492 RHSType
->isObjCObjectPointerType()) {
12493 const PointerType
*LPT
= LHSType
->getAs
<PointerType
>();
12494 const PointerType
*RPT
= RHSType
->getAs
<PointerType
>();
12496 bool LPtrToVoid
= LPT
? LPT
->getPointeeType()->isVoidType() : false;
12497 bool RPtrToVoid
= RPT
? RPT
->getPointeeType()->isVoidType() : false;
12499 if (!LPtrToVoid
&& !RPtrToVoid
&&
12500 !Context
.typesAreCompatible(LHSType
, RHSType
)) {
12501 diagnoseDistinctPointerComparison(*this, Loc
, LHS
, RHS
,
12504 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12505 // the RHS, but we have test coverage for this behavior.
12506 // FIXME: Consider using convertPointersToCompositeType in C++.
12507 if (LHSIsNull
&& !RHSIsNull
) {
12508 Expr
*E
= LHS
.get();
12509 if (getLangOpts().ObjCAutoRefCount
)
12510 ObjC().CheckObjCConversion(SourceRange(), RHSType
, E
,
12511 CheckedConversionKind::Implicit
);
12512 LHS
= ImpCastExprToType(E
, RHSType
,
12513 RPT
? CK_BitCast
:CK_CPointerToObjCPointerCast
);
12516 Expr
*E
= RHS
.get();
12517 if (getLangOpts().ObjCAutoRefCount
)
12518 ObjC().CheckObjCConversion(SourceRange(), LHSType
, E
,
12519 CheckedConversionKind::Implicit
,
12521 /*DiagnoseCFAudited=*/false, Opc
);
12522 RHS
= ImpCastExprToType(E
, LHSType
,
12523 LPT
? CK_BitCast
:CK_CPointerToObjCPointerCast
);
12525 return computeResultTy();
12527 if (LHSType
->isObjCObjectPointerType() &&
12528 RHSType
->isObjCObjectPointerType()) {
12529 if (!Context
.areComparableObjCPointerTypes(LHSType
, RHSType
))
12530 diagnoseDistinctPointerComparison(*this, Loc
, LHS
, RHS
,
12532 if (isObjCObjectLiteral(LHS
) || isObjCObjectLiteral(RHS
))
12533 diagnoseObjCLiteralComparison(*this, Loc
, LHS
, RHS
, Opc
);
12535 if (LHSIsNull
&& !RHSIsNull
)
12536 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_BitCast
);
12538 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_BitCast
);
12539 return computeResultTy();
12542 if (!IsOrdered
&& LHSType
->isBlockPointerType() &&
12543 RHSType
->isBlockCompatibleObjCPointerType(Context
)) {
12544 LHS
= ImpCastExprToType(LHS
.get(), RHSType
,
12545 CK_BlockPointerToObjCPointerCast
);
12546 return computeResultTy();
12547 } else if (!IsOrdered
&&
12548 LHSType
->isBlockCompatibleObjCPointerType(Context
) &&
12549 RHSType
->isBlockPointerType()) {
12550 RHS
= ImpCastExprToType(RHS
.get(), LHSType
,
12551 CK_BlockPointerToObjCPointerCast
);
12552 return computeResultTy();
12555 if ((LHSType
->isAnyPointerType() && RHSType
->isIntegerType()) ||
12556 (LHSType
->isIntegerType() && RHSType
->isAnyPointerType())) {
12557 unsigned DiagID
= 0;
12558 bool isError
= false;
12559 if (LangOpts
.DebuggerSupport
) {
12560 // Under a debugger, allow the comparison of pointers to integers,
12561 // since users tend to want to compare addresses.
12562 } else if ((LHSIsNull
&& LHSType
->isIntegerType()) ||
12563 (RHSIsNull
&& RHSType
->isIntegerType())) {
12565 isError
= getLangOpts().CPlusPlus
;
12567 isError
? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12568 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero
;
12570 } else if (getLangOpts().CPlusPlus
) {
12571 DiagID
= diag::err_typecheck_comparison_of_pointer_integer
;
12573 } else if (IsOrdered
)
12574 DiagID
= diag::ext_typecheck_ordered_comparison_of_pointer_integer
;
12576 DiagID
= diag::ext_typecheck_comparison_of_pointer_integer
;
12580 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
12581 << RHS
.get()->getSourceRange();
12586 if (LHSType
->isIntegerType())
12587 LHS
= ImpCastExprToType(LHS
.get(), RHSType
,
12588 LHSIsNull
? CK_NullToPointer
: CK_IntegralToPointer
);
12590 RHS
= ImpCastExprToType(RHS
.get(), LHSType
,
12591 RHSIsNull
? CK_NullToPointer
: CK_IntegralToPointer
);
12592 return computeResultTy();
12595 // Handle block pointers.
12596 if (!IsOrdered
&& RHSIsNull
12597 && LHSType
->isBlockPointerType() && RHSType
->isIntegerType()) {
12598 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_NullToPointer
);
12599 return computeResultTy();
12601 if (!IsOrdered
&& LHSIsNull
12602 && LHSType
->isIntegerType() && RHSType
->isBlockPointerType()) {
12603 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_NullToPointer
);
12604 return computeResultTy();
12607 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12608 if (LHSType
->isClkEventT() && RHSType
->isClkEventT()) {
12609 return computeResultTy();
12612 if (LHSType
->isQueueT() && RHSType
->isQueueT()) {
12613 return computeResultTy();
12616 if (LHSIsNull
&& RHSType
->isQueueT()) {
12617 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_NullToPointer
);
12618 return computeResultTy();
12621 if (LHSType
->isQueueT() && RHSIsNull
) {
12622 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_NullToPointer
);
12623 return computeResultTy();
12627 return InvalidOperands(Loc
, LHS
, RHS
);
12630 QualType
Sema::GetSignedVectorType(QualType V
) {
12631 const VectorType
*VTy
= V
->castAs
<VectorType
>();
12632 unsigned TypeSize
= Context
.getTypeSize(VTy
->getElementType());
12634 if (isa
<ExtVectorType
>(VTy
)) {
12635 if (VTy
->isExtVectorBoolType())
12636 return Context
.getExtVectorType(Context
.BoolTy
, VTy
->getNumElements());
12637 if (TypeSize
== Context
.getTypeSize(Context
.CharTy
))
12638 return Context
.getExtVectorType(Context
.CharTy
, VTy
->getNumElements());
12639 if (TypeSize
== Context
.getTypeSize(Context
.ShortTy
))
12640 return Context
.getExtVectorType(Context
.ShortTy
, VTy
->getNumElements());
12641 if (TypeSize
== Context
.getTypeSize(Context
.IntTy
))
12642 return Context
.getExtVectorType(Context
.IntTy
, VTy
->getNumElements());
12643 if (TypeSize
== Context
.getTypeSize(Context
.Int128Ty
))
12644 return Context
.getExtVectorType(Context
.Int128Ty
, VTy
->getNumElements());
12645 if (TypeSize
== Context
.getTypeSize(Context
.LongTy
))
12646 return Context
.getExtVectorType(Context
.LongTy
, VTy
->getNumElements());
12647 assert(TypeSize
== Context
.getTypeSize(Context
.LongLongTy
) &&
12648 "Unhandled vector element size in vector compare");
12649 return Context
.getExtVectorType(Context
.LongLongTy
, VTy
->getNumElements());
12652 if (TypeSize
== Context
.getTypeSize(Context
.Int128Ty
))
12653 return Context
.getVectorType(Context
.Int128Ty
, VTy
->getNumElements(),
12654 VectorKind::Generic
);
12655 if (TypeSize
== Context
.getTypeSize(Context
.LongLongTy
))
12656 return Context
.getVectorType(Context
.LongLongTy
, VTy
->getNumElements(),
12657 VectorKind::Generic
);
12658 if (TypeSize
== Context
.getTypeSize(Context
.LongTy
))
12659 return Context
.getVectorType(Context
.LongTy
, VTy
->getNumElements(),
12660 VectorKind::Generic
);
12661 if (TypeSize
== Context
.getTypeSize(Context
.IntTy
))
12662 return Context
.getVectorType(Context
.IntTy
, VTy
->getNumElements(),
12663 VectorKind::Generic
);
12664 if (TypeSize
== Context
.getTypeSize(Context
.ShortTy
))
12665 return Context
.getVectorType(Context
.ShortTy
, VTy
->getNumElements(),
12666 VectorKind::Generic
);
12667 assert(TypeSize
== Context
.getTypeSize(Context
.CharTy
) &&
12668 "Unhandled vector element size in vector compare");
12669 return Context
.getVectorType(Context
.CharTy
, VTy
->getNumElements(),
12670 VectorKind::Generic
);
12673 QualType
Sema::GetSignedSizelessVectorType(QualType V
) {
12674 const BuiltinType
*VTy
= V
->castAs
<BuiltinType
>();
12675 assert(VTy
->isSizelessBuiltinType() && "expected sizeless type");
12677 const QualType ETy
= V
->getSveEltType(Context
);
12678 const auto TypeSize
= Context
.getTypeSize(ETy
);
12680 const QualType IntTy
= Context
.getIntTypeForBitwidth(TypeSize
, true);
12681 const llvm::ElementCount VecSize
= Context
.getBuiltinVectorTypeInfo(VTy
).EC
;
12682 return Context
.getScalableVectorType(IntTy
, VecSize
.getKnownMinValue());
12685 QualType
Sema::CheckVectorCompareOperands(ExprResult
&LHS
, ExprResult
&RHS
,
12686 SourceLocation Loc
,
12687 BinaryOperatorKind Opc
) {
12688 if (Opc
== BO_Cmp
) {
12689 Diag(Loc
, diag::err_three_way_vector_comparison
);
12693 // Check to make sure we're operating on vectors of the same type and width,
12694 // Allowing one side to be a scalar of element type.
12696 CheckVectorOperands(LHS
, RHS
, Loc
, /*isCompAssign*/ false,
12697 /*AllowBothBool*/ true,
12698 /*AllowBoolConversions*/ getLangOpts().ZVector
,
12699 /*AllowBooleanOperation*/ true,
12700 /*ReportInvalid*/ true);
12701 if (vType
.isNull())
12704 QualType LHSType
= LHS
.get()->getType();
12706 // Determine the return type of a vector compare. By default clang will return
12707 // a scalar for all vector compares except vector bool and vector pixel.
12708 // With the gcc compiler we will always return a vector type and with the xl
12709 // compiler we will always return a scalar type. This switch allows choosing
12710 // which behavior is prefered.
12711 if (getLangOpts().AltiVec
) {
12712 switch (getLangOpts().getAltivecSrcCompat()) {
12713 case LangOptions::AltivecSrcCompatKind::Mixed
:
12714 // If AltiVec, the comparison results in a numeric type, i.e.
12715 // bool for C++, int for C
12716 if (vType
->castAs
<VectorType
>()->getVectorKind() ==
12717 VectorKind::AltiVecVector
)
12718 return Context
.getLogicalOperationType();
12720 Diag(Loc
, diag::warn_deprecated_altivec_src_compat
);
12722 case LangOptions::AltivecSrcCompatKind::GCC
:
12723 // For GCC we always return the vector type.
12725 case LangOptions::AltivecSrcCompatKind::XL
:
12726 return Context
.getLogicalOperationType();
12731 // For non-floating point types, check for self-comparisons of the form
12732 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12733 // often indicate logic errors in the program.
12734 diagnoseTautologicalComparison(*this, Loc
, LHS
.get(), RHS
.get(), Opc
);
12736 // Check for comparisons of floating point operands using != and ==.
12737 if (LHSType
->hasFloatingRepresentation()) {
12738 assert(RHS
.get()->getType()->hasFloatingRepresentation());
12739 CheckFloatComparison(Loc
, LHS
.get(), RHS
.get(), Opc
);
12742 // Return a signed type for the vector.
12743 return GetSignedVectorType(vType
);
12746 QualType
Sema::CheckSizelessVectorCompareOperands(ExprResult
&LHS
,
12748 SourceLocation Loc
,
12749 BinaryOperatorKind Opc
) {
12750 if (Opc
== BO_Cmp
) {
12751 Diag(Loc
, diag::err_three_way_vector_comparison
);
12755 // Check to make sure we're operating on vectors of the same type and width,
12756 // Allowing one side to be a scalar of element type.
12757 QualType vType
= CheckSizelessVectorOperands(
12758 LHS
, RHS
, Loc
, /*isCompAssign*/ false, ACK_Comparison
);
12760 if (vType
.isNull())
12763 QualType LHSType
= LHS
.get()->getType();
12765 // For non-floating point types, check for self-comparisons of the form
12766 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12767 // often indicate logic errors in the program.
12768 diagnoseTautologicalComparison(*this, Loc
, LHS
.get(), RHS
.get(), Opc
);
12770 // Check for comparisons of floating point operands using != and ==.
12771 if (LHSType
->hasFloatingRepresentation()) {
12772 assert(RHS
.get()->getType()->hasFloatingRepresentation());
12773 CheckFloatComparison(Loc
, LHS
.get(), RHS
.get(), Opc
);
12776 const BuiltinType
*LHSBuiltinTy
= LHSType
->getAs
<BuiltinType
>();
12777 const BuiltinType
*RHSBuiltinTy
= RHS
.get()->getType()->getAs
<BuiltinType
>();
12779 if (LHSBuiltinTy
&& RHSBuiltinTy
&& LHSBuiltinTy
->isSVEBool() &&
12780 RHSBuiltinTy
->isSVEBool())
12783 // Return a signed type for the vector.
12784 return GetSignedSizelessVectorType(vType
);
12787 static void diagnoseXorMisusedAsPow(Sema
&S
, const ExprResult
&XorLHS
,
12788 const ExprResult
&XorRHS
,
12789 const SourceLocation Loc
) {
12790 // Do not diagnose macros.
12791 if (Loc
.isMacroID())
12794 // Do not diagnose if both LHS and RHS are macros.
12795 if (XorLHS
.get()->getExprLoc().isMacroID() &&
12796 XorRHS
.get()->getExprLoc().isMacroID())
12799 bool Negative
= false;
12800 bool ExplicitPlus
= false;
12801 const auto *LHSInt
= dyn_cast
<IntegerLiteral
>(XorLHS
.get());
12802 const auto *RHSInt
= dyn_cast
<IntegerLiteral
>(XorRHS
.get());
12807 // Check negative literals.
12808 if (const auto *UO
= dyn_cast
<UnaryOperator
>(XorRHS
.get())) {
12809 UnaryOperatorKind Opc
= UO
->getOpcode();
12810 if (Opc
!= UO_Minus
&& Opc
!= UO_Plus
)
12812 RHSInt
= dyn_cast
<IntegerLiteral
>(UO
->getSubExpr());
12815 Negative
= (Opc
== UO_Minus
);
12816 ExplicitPlus
= !Negative
;
12822 const llvm::APInt
&LeftSideValue
= LHSInt
->getValue();
12823 llvm::APInt RightSideValue
= RHSInt
->getValue();
12824 if (LeftSideValue
!= 2 && LeftSideValue
!= 10)
12827 if (LeftSideValue
.getBitWidth() != RightSideValue
.getBitWidth())
12830 CharSourceRange ExprRange
= CharSourceRange::getCharRange(
12831 LHSInt
->getBeginLoc(), S
.getLocForEndOfToken(RHSInt
->getLocation()));
12832 llvm::StringRef ExprStr
=
12833 Lexer::getSourceText(ExprRange
, S
.getSourceManager(), S
.getLangOpts());
12835 CharSourceRange XorRange
=
12836 CharSourceRange::getCharRange(Loc
, S
.getLocForEndOfToken(Loc
));
12837 llvm::StringRef XorStr
=
12838 Lexer::getSourceText(XorRange
, S
.getSourceManager(), S
.getLangOpts());
12839 // Do not diagnose if xor keyword/macro is used.
12840 if (XorStr
== "xor")
12843 std::string LHSStr
= std::string(Lexer::getSourceText(
12844 CharSourceRange::getTokenRange(LHSInt
->getSourceRange()),
12845 S
.getSourceManager(), S
.getLangOpts()));
12846 std::string RHSStr
= std::string(Lexer::getSourceText(
12847 CharSourceRange::getTokenRange(RHSInt
->getSourceRange()),
12848 S
.getSourceManager(), S
.getLangOpts()));
12851 RightSideValue
= -RightSideValue
;
12852 RHSStr
= "-" + RHSStr
;
12853 } else if (ExplicitPlus
) {
12854 RHSStr
= "+" + RHSStr
;
12857 StringRef LHSStrRef
= LHSStr
;
12858 StringRef RHSStrRef
= RHSStr
;
12859 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12861 if (LHSStrRef
.starts_with("0b") || LHSStrRef
.starts_with("0B") ||
12862 RHSStrRef
.starts_with("0b") || RHSStrRef
.starts_with("0B") ||
12863 LHSStrRef
.starts_with("0x") || LHSStrRef
.starts_with("0X") ||
12864 RHSStrRef
.starts_with("0x") || RHSStrRef
.starts_with("0X") ||
12865 (LHSStrRef
.size() > 1 && LHSStrRef
.starts_with("0")) ||
12866 (RHSStrRef
.size() > 1 && RHSStrRef
.starts_with("0")) ||
12867 LHSStrRef
.contains('\'') || RHSStrRef
.contains('\''))
12871 S
.getLangOpts().CPlusPlus
|| S
.getPreprocessor().isMacroDefined("xor");
12872 const llvm::APInt XorValue
= LeftSideValue
^ RightSideValue
;
12873 int64_t RightSideIntValue
= RightSideValue
.getSExtValue();
12874 if (LeftSideValue
== 2 && RightSideIntValue
>= 0) {
12875 std::string SuggestedExpr
= "1 << " + RHSStr
;
12876 bool Overflow
= false;
12877 llvm::APInt One
= (LeftSideValue
- 1);
12878 llvm::APInt PowValue
= One
.sshl_ov(RightSideValue
, Overflow
);
12880 if (RightSideIntValue
< 64)
12881 S
.Diag(Loc
, diag::warn_xor_used_as_pow_base
)
12882 << ExprStr
<< toString(XorValue
, 10, true) << ("1LL << " + RHSStr
)
12883 << FixItHint::CreateReplacement(ExprRange
, "1LL << " + RHSStr
);
12884 else if (RightSideIntValue
== 64)
12885 S
.Diag(Loc
, diag::warn_xor_used_as_pow
)
12886 << ExprStr
<< toString(XorValue
, 10, true);
12890 S
.Diag(Loc
, diag::warn_xor_used_as_pow_base_extra
)
12891 << ExprStr
<< toString(XorValue
, 10, true) << SuggestedExpr
12892 << toString(PowValue
, 10, true)
12893 << FixItHint::CreateReplacement(
12894 ExprRange
, (RightSideIntValue
== 0) ? "1" : SuggestedExpr
);
12897 S
.Diag(Loc
, diag::note_xor_used_as_pow_silence
)
12898 << ("0x2 ^ " + RHSStr
) << SuggestXor
;
12899 } else if (LeftSideValue
== 10) {
12900 std::string SuggestedValue
= "1e" + std::to_string(RightSideIntValue
);
12901 S
.Diag(Loc
, diag::warn_xor_used_as_pow_base
)
12902 << ExprStr
<< toString(XorValue
, 10, true) << SuggestedValue
12903 << FixItHint::CreateReplacement(ExprRange
, SuggestedValue
);
12904 S
.Diag(Loc
, diag::note_xor_used_as_pow_silence
)
12905 << ("0xA ^ " + RHSStr
) << SuggestXor
;
12909 QualType
Sema::CheckVectorLogicalOperands(ExprResult
&LHS
, ExprResult
&RHS
,
12910 SourceLocation Loc
,
12911 BinaryOperatorKind Opc
) {
12912 // Ensure that either both operands are of the same vector type, or
12913 // one operand is of a vector type and the other is of its element type.
12914 QualType vType
= CheckVectorOperands(LHS
, RHS
, Loc
, false,
12915 /*AllowBothBool*/ true,
12916 /*AllowBoolConversions*/ false,
12917 /*AllowBooleanOperation*/ false,
12918 /*ReportInvalid*/ false);
12919 if (vType
.isNull())
12920 return InvalidOperands(Loc
, LHS
, RHS
);
12921 if (getLangOpts().OpenCL
&&
12922 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
12923 vType
->hasFloatingRepresentation())
12924 return InvalidOperands(Loc
, LHS
, RHS
);
12925 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12926 // usage of the logical operators && and || with vectors in C. This
12927 // check could be notionally dropped.
12928 if (!getLangOpts().CPlusPlus
&&
12929 !(isa
<ExtVectorType
>(vType
->getAs
<VectorType
>())))
12930 return InvalidLogicalVectorOperands(Loc
, LHS
, RHS
);
12931 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
12932 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
12933 // `select` functions.
12934 if (getLangOpts().HLSL
&&
12935 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021
) {
12936 (void)InvalidOperands(Loc
, LHS
, RHS
);
12937 HLSL().emitLogicalOperatorFixIt(LHS
.get(), RHS
.get(), Opc
);
12941 return GetSignedVectorType(LHS
.get()->getType());
12944 QualType
Sema::CheckMatrixElementwiseOperands(ExprResult
&LHS
, ExprResult
&RHS
,
12945 SourceLocation Loc
,
12946 bool IsCompAssign
) {
12947 if (!IsCompAssign
) {
12948 LHS
= DefaultFunctionArrayLvalueConversion(LHS
.get());
12949 if (LHS
.isInvalid())
12952 RHS
= DefaultFunctionArrayLvalueConversion(RHS
.get());
12953 if (RHS
.isInvalid())
12956 // For conversion purposes, we ignore any qualifiers.
12957 // For example, "const float" and "float" are equivalent.
12958 QualType LHSType
= LHS
.get()->getType().getUnqualifiedType();
12959 QualType RHSType
= RHS
.get()->getType().getUnqualifiedType();
12961 const MatrixType
*LHSMatType
= LHSType
->getAs
<MatrixType
>();
12962 const MatrixType
*RHSMatType
= RHSType
->getAs
<MatrixType
>();
12963 assert((LHSMatType
|| RHSMatType
) && "At least one operand must be a matrix");
12965 if (Context
.hasSameType(LHSType
, RHSType
))
12966 return Context
.getCommonSugaredType(LHSType
, RHSType
);
12968 // Type conversion may change LHS/RHS. Keep copies to the original results, in
12969 // case we have to return InvalidOperands.
12970 ExprResult OriginalLHS
= LHS
;
12971 ExprResult OriginalRHS
= RHS
;
12972 if (LHSMatType
&& !RHSMatType
) {
12973 RHS
= tryConvertExprToType(RHS
.get(), LHSMatType
->getElementType());
12974 if (!RHS
.isInvalid())
12977 return InvalidOperands(Loc
, OriginalLHS
, OriginalRHS
);
12980 if (!LHSMatType
&& RHSMatType
) {
12981 LHS
= tryConvertExprToType(LHS
.get(), RHSMatType
->getElementType());
12982 if (!LHS
.isInvalid())
12984 return InvalidOperands(Loc
, OriginalLHS
, OriginalRHS
);
12987 return InvalidOperands(Loc
, LHS
, RHS
);
12990 QualType
Sema::CheckMatrixMultiplyOperands(ExprResult
&LHS
, ExprResult
&RHS
,
12991 SourceLocation Loc
,
12992 bool IsCompAssign
) {
12993 if (!IsCompAssign
) {
12994 LHS
= DefaultFunctionArrayLvalueConversion(LHS
.get());
12995 if (LHS
.isInvalid())
12998 RHS
= DefaultFunctionArrayLvalueConversion(RHS
.get());
12999 if (RHS
.isInvalid())
13002 auto *LHSMatType
= LHS
.get()->getType()->getAs
<ConstantMatrixType
>();
13003 auto *RHSMatType
= RHS
.get()->getType()->getAs
<ConstantMatrixType
>();
13004 assert((LHSMatType
|| RHSMatType
) && "At least one operand must be a matrix");
13006 if (LHSMatType
&& RHSMatType
) {
13007 if (LHSMatType
->getNumColumns() != RHSMatType
->getNumRows())
13008 return InvalidOperands(Loc
, LHS
, RHS
);
13010 if (Context
.hasSameType(LHSMatType
, RHSMatType
))
13011 return Context
.getCommonSugaredType(
13012 LHS
.get()->getType().getUnqualifiedType(),
13013 RHS
.get()->getType().getUnqualifiedType());
13015 QualType LHSELTy
= LHSMatType
->getElementType(),
13016 RHSELTy
= RHSMatType
->getElementType();
13017 if (!Context
.hasSameType(LHSELTy
, RHSELTy
))
13018 return InvalidOperands(Loc
, LHS
, RHS
);
13020 return Context
.getConstantMatrixType(
13021 Context
.getCommonSugaredType(LHSELTy
, RHSELTy
),
13022 LHSMatType
->getNumRows(), RHSMatType
->getNumColumns());
13024 return CheckMatrixElementwiseOperands(LHS
, RHS
, Loc
, IsCompAssign
);
13027 static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc
) {
13041 inline QualType
Sema::CheckBitwiseOperands(ExprResult
&LHS
, ExprResult
&RHS
,
13042 SourceLocation Loc
,
13043 BinaryOperatorKind Opc
) {
13044 checkArithmeticNull(*this, LHS
, RHS
, Loc
, /*IsCompare=*/false);
13046 bool IsCompAssign
=
13047 Opc
== BO_AndAssign
|| Opc
== BO_OrAssign
|| Opc
== BO_XorAssign
;
13049 bool LegalBoolVecOperator
= isLegalBoolVectorBinaryOp(Opc
);
13051 if (LHS
.get()->getType()->isVectorType() ||
13052 RHS
.get()->getType()->isVectorType()) {
13053 if (LHS
.get()->getType()->hasIntegerRepresentation() &&
13054 RHS
.get()->getType()->hasIntegerRepresentation())
13055 return CheckVectorOperands(LHS
, RHS
, Loc
, IsCompAssign
,
13056 /*AllowBothBool*/ true,
13057 /*AllowBoolConversions*/ getLangOpts().ZVector
,
13058 /*AllowBooleanOperation*/ LegalBoolVecOperator
,
13059 /*ReportInvalid*/ true);
13060 return InvalidOperands(Loc
, LHS
, RHS
);
13063 if (LHS
.get()->getType()->isSveVLSBuiltinType() ||
13064 RHS
.get()->getType()->isSveVLSBuiltinType()) {
13065 if (LHS
.get()->getType()->hasIntegerRepresentation() &&
13066 RHS
.get()->getType()->hasIntegerRepresentation())
13067 return CheckSizelessVectorOperands(LHS
, RHS
, Loc
, IsCompAssign
,
13069 return InvalidOperands(Loc
, LHS
, RHS
);
13072 if (LHS
.get()->getType()->isSveVLSBuiltinType() ||
13073 RHS
.get()->getType()->isSveVLSBuiltinType()) {
13074 if (LHS
.get()->getType()->hasIntegerRepresentation() &&
13075 RHS
.get()->getType()->hasIntegerRepresentation())
13076 return CheckSizelessVectorOperands(LHS
, RHS
, Loc
, IsCompAssign
,
13078 return InvalidOperands(Loc
, LHS
, RHS
);
13082 diagnoseLogicalNotOnLHSofCheck(*this, LHS
, RHS
, Loc
, Opc
);
13084 if (LHS
.get()->getType()->hasFloatingRepresentation() ||
13085 RHS
.get()->getType()->hasFloatingRepresentation())
13086 return InvalidOperands(Loc
, LHS
, RHS
);
13088 ExprResult LHSResult
= LHS
, RHSResult
= RHS
;
13089 QualType compType
= UsualArithmeticConversions(
13090 LHSResult
, RHSResult
, Loc
, IsCompAssign
? ACK_CompAssign
: ACK_BitwiseOp
);
13091 if (LHSResult
.isInvalid() || RHSResult
.isInvalid())
13093 LHS
= LHSResult
.get();
13094 RHS
= RHSResult
.get();
13097 diagnoseXorMisusedAsPow(*this, LHS
, RHS
, Loc
);
13099 if (!compType
.isNull() && compType
->isIntegralOrUnscopedEnumerationType())
13101 return InvalidOperands(Loc
, LHS
, RHS
);
13105 inline QualType
Sema::CheckLogicalOperands(ExprResult
&LHS
, ExprResult
&RHS
,
13106 SourceLocation Loc
,
13107 BinaryOperatorKind Opc
) {
13108 // Check vector operands differently.
13109 if (LHS
.get()->getType()->isVectorType() ||
13110 RHS
.get()->getType()->isVectorType())
13111 return CheckVectorLogicalOperands(LHS
, RHS
, Loc
, Opc
);
13113 bool EnumConstantInBoolContext
= false;
13114 for (const ExprResult
&HS
: {LHS
, RHS
}) {
13115 if (const auto *DREHS
= dyn_cast
<DeclRefExpr
>(HS
.get())) {
13116 const auto *ECDHS
= dyn_cast
<EnumConstantDecl
>(DREHS
->getDecl());
13117 if (ECDHS
&& ECDHS
->getInitVal() != 0 && ECDHS
->getInitVal() != 1)
13118 EnumConstantInBoolContext
= true;
13122 if (EnumConstantInBoolContext
)
13123 Diag(Loc
, diag::warn_enum_constant_in_bool_context
);
13125 // WebAssembly tables can't be used with logical operators.
13126 QualType LHSTy
= LHS
.get()->getType();
13127 QualType RHSTy
= RHS
.get()->getType();
13128 const auto *LHSATy
= dyn_cast
<ArrayType
>(LHSTy
);
13129 const auto *RHSATy
= dyn_cast
<ArrayType
>(RHSTy
);
13130 if ((LHSATy
&& LHSATy
->getElementType().isWebAssemblyReferenceType()) ||
13131 (RHSATy
&& RHSATy
->getElementType().isWebAssemblyReferenceType())) {
13132 return InvalidOperands(Loc
, LHS
, RHS
);
13135 // Diagnose cases where the user write a logical and/or but probably meant a
13136 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13138 if (!EnumConstantInBoolContext
&& LHS
.get()->getType()->isIntegerType() &&
13139 !LHS
.get()->getType()->isBooleanType() &&
13140 RHS
.get()->getType()->isIntegerType() && !RHS
.get()->isValueDependent() &&
13141 // Don't warn in macros or template instantiations.
13142 !Loc
.isMacroID() && !inTemplateInstantiation()) {
13143 // If the RHS can be constant folded, and if it constant folds to something
13144 // that isn't 0 or 1 (which indicate a potential logical operation that
13145 // happened to fold to true/false) then warn.
13146 // Parens on the RHS are ignored.
13147 Expr::EvalResult EVResult
;
13148 if (RHS
.get()->EvaluateAsInt(EVResult
, Context
)) {
13149 llvm::APSInt Result
= EVResult
.Val
.getInt();
13150 if ((getLangOpts().CPlusPlus
&& !RHS
.get()->getType()->isBooleanType() &&
13151 !RHS
.get()->getExprLoc().isMacroID()) ||
13152 (Result
!= 0 && Result
!= 1)) {
13153 Diag(Loc
, diag::warn_logical_instead_of_bitwise
)
13154 << RHS
.get()->getSourceRange() << (Opc
== BO_LAnd
? "&&" : "||");
13155 // Suggest replacing the logical operator with the bitwise version
13156 Diag(Loc
, diag::note_logical_instead_of_bitwise_change_operator
)
13157 << (Opc
== BO_LAnd
? "&" : "|")
13158 << FixItHint::CreateReplacement(
13159 SourceRange(Loc
, getLocForEndOfToken(Loc
)),
13160 Opc
== BO_LAnd
? "&" : "|");
13161 if (Opc
== BO_LAnd
)
13162 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13163 Diag(Loc
, diag::note_logical_instead_of_bitwise_remove_constant
)
13164 << FixItHint::CreateRemoval(
13165 SourceRange(getLocForEndOfToken(LHS
.get()->getEndLoc()),
13166 RHS
.get()->getEndLoc()));
13171 if (!Context
.getLangOpts().CPlusPlus
) {
13172 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13173 // not operate on the built-in scalar and vector float types.
13174 if (Context
.getLangOpts().OpenCL
&&
13175 Context
.getLangOpts().OpenCLVersion
< 120) {
13176 if (LHS
.get()->getType()->isFloatingType() ||
13177 RHS
.get()->getType()->isFloatingType())
13178 return InvalidOperands(Loc
, LHS
, RHS
);
13181 LHS
= UsualUnaryConversions(LHS
.get());
13182 if (LHS
.isInvalid())
13185 RHS
= UsualUnaryConversions(RHS
.get());
13186 if (RHS
.isInvalid())
13189 if (!LHS
.get()->getType()->isScalarType() ||
13190 !RHS
.get()->getType()->isScalarType())
13191 return InvalidOperands(Loc
, LHS
, RHS
);
13193 return Context
.IntTy
;
13196 // The following is safe because we only use this method for
13197 // non-overloadable operands.
13199 // C++ [expr.log.and]p1
13200 // C++ [expr.log.or]p1
13201 // The operands are both contextually converted to type bool.
13202 ExprResult LHSRes
= PerformContextuallyConvertToBool(LHS
.get());
13203 if (LHSRes
.isInvalid())
13204 return InvalidOperands(Loc
, LHS
, RHS
);
13207 ExprResult RHSRes
= PerformContextuallyConvertToBool(RHS
.get());
13208 if (RHSRes
.isInvalid())
13209 return InvalidOperands(Loc
, LHS
, RHS
);
13212 // C++ [expr.log.and]p2
13213 // C++ [expr.log.or]p2
13214 // The result is a bool.
13215 return Context
.BoolTy
;
13218 static bool IsReadonlyMessage(Expr
*E
, Sema
&S
) {
13219 const MemberExpr
*ME
= dyn_cast
<MemberExpr
>(E
);
13220 if (!ME
) return false;
13221 if (!isa
<FieldDecl
>(ME
->getMemberDecl())) return false;
13222 ObjCMessageExpr
*Base
= dyn_cast
<ObjCMessageExpr
>(
13223 ME
->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
13224 if (!Base
) return false;
13225 return Base
->getMethodDecl() != nullptr;
13228 /// Is the given expression (which must be 'const') a reference to a
13229 /// variable which was originally non-const, but which has become
13230 /// 'const' due to being captured within a block?
13231 enum NonConstCaptureKind
{ NCCK_None
, NCCK_Block
, NCCK_Lambda
};
13232 static NonConstCaptureKind
isReferenceToNonConstCapture(Sema
&S
, Expr
*E
) {
13233 assert(E
->isLValue() && E
->getType().isConstQualified());
13234 E
= E
->IgnoreParens();
13236 // Must be a reference to a declaration from an enclosing scope.
13237 DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(E
);
13238 if (!DRE
) return NCCK_None
;
13239 if (!DRE
->refersToEnclosingVariableOrCapture()) return NCCK_None
;
13241 // The declaration must be a variable which is not declared 'const'.
13242 VarDecl
*var
= dyn_cast
<VarDecl
>(DRE
->getDecl());
13243 if (!var
) return NCCK_None
;
13244 if (var
->getType().isConstQualified()) return NCCK_None
;
13245 assert(var
->hasLocalStorage() && "capture added 'const' to non-local?");
13247 // Decide whether the first capture was for a block or a lambda.
13248 DeclContext
*DC
= S
.CurContext
, *Prev
= nullptr;
13249 // Decide whether the first capture was for a block or a lambda.
13251 // For init-capture, it is possible that the variable belongs to the
13252 // template pattern of the current context.
13253 if (auto *FD
= dyn_cast
<FunctionDecl
>(DC
))
13254 if (var
->isInitCapture() &&
13255 FD
->getTemplateInstantiationPattern() == var
->getDeclContext())
13257 if (DC
== var
->getDeclContext())
13260 DC
= DC
->getParent();
13262 // Unless we have an init-capture, we've gone one step too far.
13263 if (!var
->isInitCapture())
13265 return (isa
<BlockDecl
>(DC
) ? NCCK_Block
: NCCK_Lambda
);
13268 static bool IsTypeModifiable(QualType Ty
, bool IsDereference
) {
13269 Ty
= Ty
.getNonReferenceType();
13270 if (IsDereference
&& Ty
->isPointerType())
13271 Ty
= Ty
->getPointeeType();
13272 return !Ty
.isConstQualified();
13275 // Update err_typecheck_assign_const and note_typecheck_assign_const
13276 // when this enum is changed.
13283 ConstUnknown
, // Keep as last element
13286 /// Emit the "read-only variable not assignable" error and print notes to give
13287 /// more information about why the variable is not assignable, such as pointing
13288 /// to the declaration of a const variable, showing that a method is const, or
13289 /// that the function is returning a const reference.
13290 static void DiagnoseConstAssignment(Sema
&S
, const Expr
*E
,
13291 SourceLocation Loc
) {
13292 SourceRange ExprRange
= E
->getSourceRange();
13294 // Only emit one error on the first const found. All other consts will emit
13295 // a note to the error.
13296 bool DiagnosticEmitted
= false;
13298 // Track if the current expression is the result of a dereference, and if the
13299 // next checked expression is the result of a dereference.
13300 bool IsDereference
= false;
13301 bool NextIsDereference
= false;
13303 // Loop to process MemberExpr chains.
13305 IsDereference
= NextIsDereference
;
13307 E
= E
->IgnoreImplicit()->IgnoreParenImpCasts();
13308 if (const MemberExpr
*ME
= dyn_cast
<MemberExpr
>(E
)) {
13309 NextIsDereference
= ME
->isArrow();
13310 const ValueDecl
*VD
= ME
->getMemberDecl();
13311 if (const FieldDecl
*Field
= dyn_cast
<FieldDecl
>(VD
)) {
13312 // Mutable fields can be modified even if the class is const.
13313 if (Field
->isMutable()) {
13314 assert(DiagnosticEmitted
&& "Expected diagnostic not emitted.");
13318 if (!IsTypeModifiable(Field
->getType(), IsDereference
)) {
13319 if (!DiagnosticEmitted
) {
13320 S
.Diag(Loc
, diag::err_typecheck_assign_const
)
13321 << ExprRange
<< ConstMember
<< false /*static*/ << Field
13322 << Field
->getType();
13323 DiagnosticEmitted
= true;
13325 S
.Diag(VD
->getLocation(), diag::note_typecheck_assign_const
)
13326 << ConstMember
<< false /*static*/ << Field
<< Field
->getType()
13327 << Field
->getSourceRange();
13331 } else if (const VarDecl
*VDecl
= dyn_cast
<VarDecl
>(VD
)) {
13332 if (VDecl
->getType().isConstQualified()) {
13333 if (!DiagnosticEmitted
) {
13334 S
.Diag(Loc
, diag::err_typecheck_assign_const
)
13335 << ExprRange
<< ConstMember
<< true /*static*/ << VDecl
13336 << VDecl
->getType();
13337 DiagnosticEmitted
= true;
13339 S
.Diag(VD
->getLocation(), diag::note_typecheck_assign_const
)
13340 << ConstMember
<< true /*static*/ << VDecl
<< VDecl
->getType()
13341 << VDecl
->getSourceRange();
13343 // Static fields do not inherit constness from parents.
13346 break; // End MemberExpr
13347 } else if (const ArraySubscriptExpr
*ASE
=
13348 dyn_cast
<ArraySubscriptExpr
>(E
)) {
13349 E
= ASE
->getBase()->IgnoreParenImpCasts();
13351 } else if (const ExtVectorElementExpr
*EVE
=
13352 dyn_cast
<ExtVectorElementExpr
>(E
)) {
13353 E
= EVE
->getBase()->IgnoreParenImpCasts();
13359 if (const CallExpr
*CE
= dyn_cast
<CallExpr
>(E
)) {
13361 const FunctionDecl
*FD
= CE
->getDirectCallee();
13362 if (FD
&& !IsTypeModifiable(FD
->getReturnType(), IsDereference
)) {
13363 if (!DiagnosticEmitted
) {
13364 S
.Diag(Loc
, diag::err_typecheck_assign_const
) << ExprRange
13365 << ConstFunction
<< FD
;
13366 DiagnosticEmitted
= true;
13368 S
.Diag(FD
->getReturnTypeSourceRange().getBegin(),
13369 diag::note_typecheck_assign_const
)
13370 << ConstFunction
<< FD
<< FD
->getReturnType()
13371 << FD
->getReturnTypeSourceRange();
13373 } else if (const DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(E
)) {
13374 // Point to variable declaration.
13375 if (const ValueDecl
*VD
= DRE
->getDecl()) {
13376 if (!IsTypeModifiable(VD
->getType(), IsDereference
)) {
13377 if (!DiagnosticEmitted
) {
13378 S
.Diag(Loc
, diag::err_typecheck_assign_const
)
13379 << ExprRange
<< ConstVariable
<< VD
<< VD
->getType();
13380 DiagnosticEmitted
= true;
13382 S
.Diag(VD
->getLocation(), diag::note_typecheck_assign_const
)
13383 << ConstVariable
<< VD
<< VD
->getType() << VD
->getSourceRange();
13386 } else if (isa
<CXXThisExpr
>(E
)) {
13387 if (const DeclContext
*DC
= S
.getFunctionLevelDeclContext()) {
13388 if (const CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(DC
)) {
13389 if (MD
->isConst()) {
13390 if (!DiagnosticEmitted
) {
13391 S
.Diag(Loc
, diag::err_typecheck_assign_const
) << ExprRange
13392 << ConstMethod
<< MD
;
13393 DiagnosticEmitted
= true;
13395 S
.Diag(MD
->getLocation(), diag::note_typecheck_assign_const
)
13396 << ConstMethod
<< MD
<< MD
->getSourceRange();
13402 if (DiagnosticEmitted
)
13405 // Can't determine a more specific message, so display the generic error.
13406 S
.Diag(Loc
, diag::err_typecheck_assign_const
) << ExprRange
<< ConstUnknown
;
13409 enum OriginalExprKind
{
13415 static void DiagnoseRecursiveConstFields(Sema
&S
, const ValueDecl
*VD
,
13416 const RecordType
*Ty
,
13417 SourceLocation Loc
, SourceRange Range
,
13418 OriginalExprKind OEK
,
13419 bool &DiagnosticEmitted
) {
13420 std::vector
<const RecordType
*> RecordTypeList
;
13421 RecordTypeList
.push_back(Ty
);
13422 unsigned NextToCheckIndex
= 0;
13423 // We walk the record hierarchy breadth-first to ensure that we print
13424 // diagnostics in field nesting order.
13425 while (RecordTypeList
.size() > NextToCheckIndex
) {
13426 bool IsNested
= NextToCheckIndex
> 0;
13427 for (const FieldDecl
*Field
:
13428 RecordTypeList
[NextToCheckIndex
]->getDecl()->fields()) {
13429 // First, check every field for constness.
13430 QualType FieldTy
= Field
->getType();
13431 if (FieldTy
.isConstQualified()) {
13432 if (!DiagnosticEmitted
) {
13433 S
.Diag(Loc
, diag::err_typecheck_assign_const
)
13434 << Range
<< NestedConstMember
<< OEK
<< VD
13435 << IsNested
<< Field
;
13436 DiagnosticEmitted
= true;
13438 S
.Diag(Field
->getLocation(), diag::note_typecheck_assign_const
)
13439 << NestedConstMember
<< IsNested
<< Field
13440 << FieldTy
<< Field
->getSourceRange();
13443 // Then we append it to the list to check next in order.
13444 FieldTy
= FieldTy
.getCanonicalType();
13445 if (const auto *FieldRecTy
= FieldTy
->getAs
<RecordType
>()) {
13446 if (!llvm::is_contained(RecordTypeList
, FieldRecTy
))
13447 RecordTypeList
.push_back(FieldRecTy
);
13450 ++NextToCheckIndex
;
13454 /// Emit an error for the case where a record we are trying to assign to has a
13455 /// const-qualified field somewhere in its hierarchy.
13456 static void DiagnoseRecursiveConstFields(Sema
&S
, const Expr
*E
,
13457 SourceLocation Loc
) {
13458 QualType Ty
= E
->getType();
13459 assert(Ty
->isRecordType() && "lvalue was not record?");
13460 SourceRange Range
= E
->getSourceRange();
13461 const RecordType
*RTy
= Ty
.getCanonicalType()->getAs
<RecordType
>();
13462 bool DiagEmitted
= false;
13464 if (const MemberExpr
*ME
= dyn_cast
<MemberExpr
>(E
))
13465 DiagnoseRecursiveConstFields(S
, ME
->getMemberDecl(), RTy
, Loc
,
13466 Range
, OEK_Member
, DiagEmitted
);
13467 else if (const DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(E
))
13468 DiagnoseRecursiveConstFields(S
, DRE
->getDecl(), RTy
, Loc
,
13469 Range
, OEK_Variable
, DiagEmitted
);
13471 DiagnoseRecursiveConstFields(S
, nullptr, RTy
, Loc
,
13472 Range
, OEK_LValue
, DiagEmitted
);
13474 DiagnoseConstAssignment(S
, E
, Loc
);
13477 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
13478 /// emit an error and return true. If so, return false.
13479 static bool CheckForModifiableLvalue(Expr
*E
, SourceLocation Loc
, Sema
&S
) {
13480 assert(!E
->hasPlaceholderType(BuiltinType::PseudoObject
));
13482 S
.CheckShadowingDeclModification(E
, Loc
);
13484 SourceLocation OrigLoc
= Loc
;
13485 Expr::isModifiableLvalueResult IsLV
= E
->isModifiableLvalue(S
.Context
,
13487 if (IsLV
== Expr::MLV_ClassTemporary
&& IsReadonlyMessage(E
, S
))
13488 IsLV
= Expr::MLV_InvalidMessageExpression
;
13489 if (IsLV
== Expr::MLV_Valid
)
13492 unsigned DiagID
= 0;
13493 bool NeedType
= false;
13494 switch (IsLV
) { // C99 6.5.16p2
13495 case Expr::MLV_ConstQualified
:
13496 // Use a specialized diagnostic when we're assigning to an object
13497 // from an enclosing function or block.
13498 if (NonConstCaptureKind NCCK
= isReferenceToNonConstCapture(S
, E
)) {
13499 if (NCCK
== NCCK_Block
)
13500 DiagID
= diag::err_block_decl_ref_not_modifiable_lvalue
;
13502 DiagID
= diag::err_lambda_decl_ref_not_modifiable_lvalue
;
13506 // In ARC, use some specialized diagnostics for occasions where we
13507 // infer 'const'. These are always pseudo-strong variables.
13508 if (S
.getLangOpts().ObjCAutoRefCount
) {
13509 DeclRefExpr
*declRef
= dyn_cast
<DeclRefExpr
>(E
->IgnoreParenCasts());
13510 if (declRef
&& isa
<VarDecl
>(declRef
->getDecl())) {
13511 VarDecl
*var
= cast
<VarDecl
>(declRef
->getDecl());
13513 // Use the normal diagnostic if it's pseudo-__strong but the
13514 // user actually wrote 'const'.
13515 if (var
->isARCPseudoStrong() &&
13516 (!var
->getTypeSourceInfo() ||
13517 !var
->getTypeSourceInfo()->getType().isConstQualified())) {
13518 // There are three pseudo-strong cases:
13520 ObjCMethodDecl
*method
= S
.getCurMethodDecl();
13521 if (method
&& var
== method
->getSelfDecl()) {
13522 DiagID
= method
->isClassMethod()
13523 ? diag::err_typecheck_arc_assign_self_class_method
13524 : diag::err_typecheck_arc_assign_self
;
13526 // - Objective-C externally_retained attribute.
13527 } else if (var
->hasAttr
<ObjCExternallyRetainedAttr
>() ||
13528 isa
<ParmVarDecl
>(var
)) {
13529 DiagID
= diag::err_typecheck_arc_assign_externally_retained
;
13531 // - fast enumeration variables
13533 DiagID
= diag::err_typecheck_arr_assign_enumeration
;
13536 SourceRange Assign
;
13537 if (Loc
!= OrigLoc
)
13538 Assign
= SourceRange(OrigLoc
, OrigLoc
);
13539 S
.Diag(Loc
, DiagID
) << E
->getSourceRange() << Assign
;
13540 // We need to preserve the AST regardless, so migration tool
13547 // If none of the special cases above are triggered, then this is a
13548 // simple const assignment.
13550 DiagnoseConstAssignment(S
, E
, Loc
);
13555 case Expr::MLV_ConstAddrSpace
:
13556 DiagnoseConstAssignment(S
, E
, Loc
);
13558 case Expr::MLV_ConstQualifiedField
:
13559 DiagnoseRecursiveConstFields(S
, E
, Loc
);
13561 case Expr::MLV_ArrayType
:
13562 case Expr::MLV_ArrayTemporary
:
13563 DiagID
= diag::err_typecheck_array_not_modifiable_lvalue
;
13566 case Expr::MLV_NotObjectType
:
13567 DiagID
= diag::err_typecheck_non_object_not_modifiable_lvalue
;
13570 case Expr::MLV_LValueCast
:
13571 DiagID
= diag::err_typecheck_lvalue_casts_not_supported
;
13573 case Expr::MLV_Valid
:
13574 llvm_unreachable("did not take early return for MLV_Valid");
13575 case Expr::MLV_InvalidExpression
:
13576 case Expr::MLV_MemberFunction
:
13577 case Expr::MLV_ClassTemporary
:
13578 DiagID
= diag::err_typecheck_expression_not_modifiable_lvalue
;
13580 case Expr::MLV_IncompleteType
:
13581 case Expr::MLV_IncompleteVoidType
:
13582 return S
.RequireCompleteType(Loc
, E
->getType(),
13583 diag::err_typecheck_incomplete_type_not_modifiable_lvalue
, E
);
13584 case Expr::MLV_DuplicateVectorComponents
:
13585 DiagID
= diag::err_typecheck_duplicate_vector_components_not_mlvalue
;
13587 case Expr::MLV_NoSetterProperty
:
13588 llvm_unreachable("readonly properties should be processed differently");
13589 case Expr::MLV_InvalidMessageExpression
:
13590 DiagID
= diag::err_readonly_message_assignment
;
13592 case Expr::MLV_SubObjCPropertySetting
:
13593 DiagID
= diag::err_no_subobject_property_setting
;
13597 SourceRange Assign
;
13598 if (Loc
!= OrigLoc
)
13599 Assign
= SourceRange(OrigLoc
, OrigLoc
);
13601 S
.Diag(Loc
, DiagID
) << E
->getType() << E
->getSourceRange() << Assign
;
13603 S
.Diag(Loc
, DiagID
) << E
->getSourceRange() << Assign
;
13607 static void CheckIdentityFieldAssignment(Expr
*LHSExpr
, Expr
*RHSExpr
,
13608 SourceLocation Loc
,
13610 if (Sema
.inTemplateInstantiation())
13612 if (Sema
.isUnevaluatedContext())
13614 if (Loc
.isInvalid() || Loc
.isMacroID())
13616 if (LHSExpr
->getExprLoc().isMacroID() || RHSExpr
->getExprLoc().isMacroID())
13620 MemberExpr
*ML
= dyn_cast
<MemberExpr
>(LHSExpr
);
13621 MemberExpr
*MR
= dyn_cast
<MemberExpr
>(RHSExpr
);
13623 if (!(isa
<CXXThisExpr
>(ML
->getBase()) && isa
<CXXThisExpr
>(MR
->getBase())))
13625 const ValueDecl
*LHSDecl
=
13626 cast
<ValueDecl
>(ML
->getMemberDecl()->getCanonicalDecl());
13627 const ValueDecl
*RHSDecl
=
13628 cast
<ValueDecl
>(MR
->getMemberDecl()->getCanonicalDecl());
13629 if (LHSDecl
!= RHSDecl
)
13631 if (LHSDecl
->getType().isVolatileQualified())
13633 if (const ReferenceType
*RefTy
= LHSDecl
->getType()->getAs
<ReferenceType
>())
13634 if (RefTy
->getPointeeType().isVolatileQualified())
13637 Sema
.Diag(Loc
, diag::warn_identity_field_assign
) << 0;
13640 // Objective-C instance variables
13641 ObjCIvarRefExpr
*OL
= dyn_cast
<ObjCIvarRefExpr
>(LHSExpr
);
13642 ObjCIvarRefExpr
*OR
= dyn_cast
<ObjCIvarRefExpr
>(RHSExpr
);
13643 if (OL
&& OR
&& OL
->getDecl() == OR
->getDecl()) {
13644 DeclRefExpr
*RL
= dyn_cast
<DeclRefExpr
>(OL
->getBase()->IgnoreImpCasts());
13645 DeclRefExpr
*RR
= dyn_cast
<DeclRefExpr
>(OR
->getBase()->IgnoreImpCasts());
13646 if (RL
&& RR
&& RL
->getDecl() == RR
->getDecl())
13647 Sema
.Diag(Loc
, diag::warn_identity_field_assign
) << 1;
13652 QualType
Sema::CheckAssignmentOperands(Expr
*LHSExpr
, ExprResult
&RHS
,
13653 SourceLocation Loc
,
13654 QualType CompoundType
,
13655 BinaryOperatorKind Opc
) {
13656 assert(!LHSExpr
->hasPlaceholderType(BuiltinType::PseudoObject
));
13658 // Verify that LHS is a modifiable lvalue, and emit error if not.
13659 if (CheckForModifiableLvalue(LHSExpr
, Loc
, *this))
13662 QualType LHSType
= LHSExpr
->getType();
13663 QualType RHSType
= CompoundType
.isNull() ? RHS
.get()->getType() :
13665 // OpenCL v1.2 s6.1.1.1 p2:
13666 // The half data type can only be used to declare a pointer to a buffer that
13667 // contains half values
13668 if (getLangOpts().OpenCL
&&
13669 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13670 LHSType
->isHalfType()) {
13671 Diag(Loc
, diag::err_opencl_half_load_store
) << 1
13672 << LHSType
.getUnqualifiedType();
13676 // WebAssembly tables can't be used on RHS of an assignment expression.
13677 if (RHSType
->isWebAssemblyTableType()) {
13678 Diag(Loc
, diag::err_wasm_table_art
) << 0;
13682 AssignConvertType ConvTy
;
13683 if (CompoundType
.isNull()) {
13684 Expr
*RHSCheck
= RHS
.get();
13686 CheckIdentityFieldAssignment(LHSExpr
, RHSCheck
, Loc
, *this);
13688 QualType
LHSTy(LHSType
);
13689 ConvTy
= CheckSingleAssignmentConstraints(LHSTy
, RHS
);
13690 if (RHS
.isInvalid())
13692 // Special case of NSObject attributes on c-style pointer types.
13693 if (ConvTy
== IncompatiblePointer
&&
13694 ((Context
.isObjCNSObjectType(LHSType
) &&
13695 RHSType
->isObjCObjectPointerType()) ||
13696 (Context
.isObjCNSObjectType(RHSType
) &&
13697 LHSType
->isObjCObjectPointerType())))
13698 ConvTy
= Compatible
;
13700 if (ConvTy
== Compatible
&&
13701 LHSType
->isObjCObjectType())
13702 Diag(Loc
, diag::err_objc_object_assignment
)
13705 // If the RHS is a unary plus or minus, check to see if they = and + are
13706 // right next to each other. If so, the user may have typo'd "x =+ 4"
13707 // instead of "x += 4".
13708 if (ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(RHSCheck
))
13709 RHSCheck
= ICE
->getSubExpr();
13710 if (UnaryOperator
*UO
= dyn_cast
<UnaryOperator
>(RHSCheck
)) {
13711 if ((UO
->getOpcode() == UO_Plus
|| UO
->getOpcode() == UO_Minus
) &&
13712 Loc
.isFileID() && UO
->getOperatorLoc().isFileID() &&
13713 // Only if the two operators are exactly adjacent.
13714 Loc
.getLocWithOffset(1) == UO
->getOperatorLoc() &&
13715 // And there is a space or other character before the subexpr of the
13716 // unary +/-. We don't want to warn on "x=-1".
13717 Loc
.getLocWithOffset(2) != UO
->getSubExpr()->getBeginLoc() &&
13718 UO
->getSubExpr()->getBeginLoc().isFileID()) {
13719 Diag(Loc
, diag::warn_not_compound_assign
)
13720 << (UO
->getOpcode() == UO_Plus
? "+" : "-")
13721 << SourceRange(UO
->getOperatorLoc(), UO
->getOperatorLoc());
13725 if (ConvTy
== Compatible
) {
13726 if (LHSType
.getObjCLifetime() == Qualifiers::OCL_Strong
) {
13727 // Warn about retain cycles where a block captures the LHS, but
13728 // not if the LHS is a simple variable into which the block is
13729 // being stored...unless that variable can be captured by reference!
13730 const Expr
*InnerLHS
= LHSExpr
->IgnoreParenCasts();
13731 const DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(InnerLHS
);
13732 if (!DRE
|| DRE
->getDecl()->hasAttr
<BlocksAttr
>())
13733 ObjC().checkRetainCycles(LHSExpr
, RHS
.get());
13736 if (LHSType
.getObjCLifetime() == Qualifiers::OCL_Strong
||
13737 LHSType
.isNonWeakInMRRWithObjCWeak(Context
)) {
13738 // It is safe to assign a weak reference into a strong variable.
13739 // Although this code can still have problems:
13740 // id x = self.weakProp;
13741 // id y = self.weakProp;
13742 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13743 // paths through the function. This should be revisited if
13744 // -Wrepeated-use-of-weak is made flow-sensitive.
13745 // For ObjCWeak only, we do not warn if the assign is to a non-weak
13746 // variable, which will be valid for the current autorelease scope.
13747 if (!Diags
.isIgnored(diag::warn_arc_repeated_use_of_weak
,
13748 RHS
.get()->getBeginLoc()))
13749 getCurFunction()->markSafeWeakUse(RHS
.get());
13751 } else if (getLangOpts().ObjCAutoRefCount
|| getLangOpts().ObjCWeak
) {
13752 checkUnsafeExprAssigns(Loc
, LHSExpr
, RHS
.get());
13756 // Compound assignment "x += y"
13757 ConvTy
= CheckAssignmentConstraints(Loc
, LHSType
, RHSType
);
13760 if (DiagnoseAssignmentResult(ConvTy
, Loc
, LHSType
, RHSType
, RHS
.get(),
13761 AssignmentAction::Assigning
))
13764 CheckForNullPointerDereference(*this, LHSExpr
);
13766 AssignedEntity AE
{LHSExpr
};
13767 checkAssignmentLifetime(*this, AE
, RHS
.get());
13769 if (getLangOpts().CPlusPlus20
&& LHSType
.isVolatileQualified()) {
13770 if (CompoundType
.isNull()) {
13771 // C++2a [expr.ass]p5:
13772 // A simple-assignment whose left operand is of a volatile-qualified
13773 // type is deprecated unless the assignment is either a discarded-value
13774 // expression or an unevaluated operand
13775 ExprEvalContexts
.back().VolatileAssignmentLHSs
.push_back(LHSExpr
);
13779 // C11 6.5.16p3: The type of an assignment expression is the type of the
13780 // left operand would have after lvalue conversion.
13781 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
13782 // qualified type, the value has the unqualified version of the type of the
13783 // lvalue; additionally, if the lvalue has atomic type, the value has the
13784 // non-atomic version of the type of the lvalue.
13785 // C++ 5.17p1: the type of the assignment expression is that of its left
13787 return getLangOpts().CPlusPlus
? LHSType
: LHSType
.getAtomicUnqualifiedType();
13790 // Scenarios to ignore if expression E is:
13791 // 1. an explicit cast expression into void
13792 // 2. a function call expression that returns void
13793 static bool IgnoreCommaOperand(const Expr
*E
, const ASTContext
&Context
) {
13794 E
= E
->IgnoreParens();
13796 if (const CastExpr
*CE
= dyn_cast
<CastExpr
>(E
)) {
13797 if (CE
->getCastKind() == CK_ToVoid
) {
13801 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13802 if (CE
->getCastKind() == CK_Dependent
&& E
->getType()->isVoidType() &&
13803 CE
->getSubExpr()->getType()->isDependentType()) {
13808 if (const auto *CE
= dyn_cast
<CallExpr
>(E
))
13809 return CE
->getCallReturnType(Context
)->isVoidType();
13813 void Sema::DiagnoseCommaOperator(const Expr
*LHS
, SourceLocation Loc
) {
13814 // No warnings in macros
13815 if (Loc
.isMacroID())
13818 // Don't warn in template instantiations.
13819 if (inTemplateInstantiation())
13822 // Scope isn't fine-grained enough to explicitly list the specific cases, so
13823 // instead, skip more than needed, then call back into here with the
13824 // CommaVisitor in SemaStmt.cpp.
13825 // The listed locations are the initialization and increment portions
13826 // of a for loop. The additional checks are on the condition of
13827 // if statements, do/while loops, and for loops.
13828 // Differences in scope flags for C89 mode requires the extra logic.
13829 const unsigned ForIncrementFlags
=
13830 getLangOpts().C99
|| getLangOpts().CPlusPlus
13831 ? Scope::ControlScope
| Scope::ContinueScope
| Scope::BreakScope
13832 : Scope::ContinueScope
| Scope::BreakScope
;
13833 const unsigned ForInitFlags
= Scope::ControlScope
| Scope::DeclScope
;
13834 const unsigned ScopeFlags
= getCurScope()->getFlags();
13835 if ((ScopeFlags
& ForIncrementFlags
) == ForIncrementFlags
||
13836 (ScopeFlags
& ForInitFlags
) == ForInitFlags
)
13839 // If there are multiple comma operators used together, get the RHS of the
13840 // of the comma operator as the LHS.
13841 while (const BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(LHS
)) {
13842 if (BO
->getOpcode() != BO_Comma
)
13844 LHS
= BO
->getRHS();
13847 // Only allow some expressions on LHS to not warn.
13848 if (IgnoreCommaOperand(LHS
, Context
))
13851 Diag(Loc
, diag::warn_comma_operator
);
13852 Diag(LHS
->getBeginLoc(), diag::note_cast_to_void
)
13853 << LHS
->getSourceRange()
13854 << FixItHint::CreateInsertion(LHS
->getBeginLoc(),
13855 LangOpts
.CPlusPlus
? "static_cast<void>("
13857 << FixItHint::CreateInsertion(PP
.getLocForEndOfToken(LHS
->getEndLoc()),
13862 static QualType
CheckCommaOperands(Sema
&S
, ExprResult
&LHS
, ExprResult
&RHS
,
13863 SourceLocation Loc
) {
13864 LHS
= S
.CheckPlaceholderExpr(LHS
.get());
13865 RHS
= S
.CheckPlaceholderExpr(RHS
.get());
13866 if (LHS
.isInvalid() || RHS
.isInvalid())
13869 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13870 // operands, but not unary promotions.
13871 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13873 // So we treat the LHS as a ignored value, and in C++ we allow the
13874 // containing site to determine what should be done with the RHS.
13875 LHS
= S
.IgnoredValueConversions(LHS
.get());
13876 if (LHS
.isInvalid())
13879 S
.DiagnoseUnusedExprResult(LHS
.get(), diag::warn_unused_comma_left_operand
);
13881 if (!S
.getLangOpts().CPlusPlus
) {
13882 RHS
= S
.DefaultFunctionArrayLvalueConversion(RHS
.get());
13883 if (RHS
.isInvalid())
13885 if (!RHS
.get()->getType()->isVoidType())
13886 S
.RequireCompleteType(Loc
, RHS
.get()->getType(),
13887 diag::err_incomplete_type
);
13890 if (!S
.getDiagnostics().isIgnored(diag::warn_comma_operator
, Loc
))
13891 S
.DiagnoseCommaOperator(LHS
.get(), Loc
);
13893 return RHS
.get()->getType();
13896 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13897 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13898 static QualType
CheckIncrementDecrementOperand(Sema
&S
, Expr
*Op
,
13900 ExprObjectKind
&OK
,
13901 SourceLocation OpLoc
, bool IsInc
,
13903 QualType ResType
= Op
->getType();
13904 // Atomic types can be used for increment / decrement where the non-atomic
13905 // versions can, so ignore the _Atomic() specifier for the purpose of
13907 if (const AtomicType
*ResAtomicType
= ResType
->getAs
<AtomicType
>())
13908 ResType
= ResAtomicType
->getValueType();
13910 assert(!ResType
.isNull() && "no type for increment/decrement expression");
13912 if (S
.getLangOpts().CPlusPlus
&& ResType
->isBooleanType()) {
13913 // Decrement of bool is not allowed.
13915 S
.Diag(OpLoc
, diag::err_decrement_bool
) << Op
->getSourceRange();
13918 // Increment of bool sets it to true, but is deprecated.
13919 S
.Diag(OpLoc
, S
.getLangOpts().CPlusPlus17
? diag::ext_increment_bool
13920 : diag::warn_increment_bool
)
13921 << Op
->getSourceRange();
13922 } else if (S
.getLangOpts().CPlusPlus
&& ResType
->isEnumeralType()) {
13923 // Error on enum increments and decrements in C++ mode
13924 S
.Diag(OpLoc
, diag::err_increment_decrement_enum
) << IsInc
<< ResType
;
13926 } else if (ResType
->isRealType()) {
13928 } else if (ResType
->isPointerType()) {
13929 // C99 6.5.2.4p2, 6.5.6p2
13930 if (!checkArithmeticOpPointerOperand(S
, OpLoc
, Op
))
13932 } else if (ResType
->isObjCObjectPointerType()) {
13933 // On modern runtimes, ObjC pointer arithmetic is forbidden.
13934 // Otherwise, we just need a complete type.
13935 if (checkArithmeticIncompletePointerType(S
, OpLoc
, Op
) ||
13936 checkArithmeticOnObjCPointer(S
, OpLoc
, Op
))
13938 } else if (ResType
->isAnyComplexType()) {
13939 // C99 does not support ++/-- on complex types, we allow as an extension.
13940 S
.Diag(OpLoc
, S
.getLangOpts().C2y
? diag::warn_c2y_compat_increment_complex
13941 : diag::ext_c2y_increment_complex
)
13942 << IsInc
<< Op
->getSourceRange();
13943 } else if (ResType
->isPlaceholderType()) {
13944 ExprResult PR
= S
.CheckPlaceholderExpr(Op
);
13945 if (PR
.isInvalid()) return QualType();
13946 return CheckIncrementDecrementOperand(S
, PR
.get(), VK
, OK
, OpLoc
,
13948 } else if (S
.getLangOpts().AltiVec
&& ResType
->isVectorType()) {
13949 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13950 } else if (S
.getLangOpts().ZVector
&& ResType
->isVectorType() &&
13951 (ResType
->castAs
<VectorType
>()->getVectorKind() !=
13952 VectorKind::AltiVecBool
)) {
13953 // The z vector extensions allow ++ and -- for non-bool vectors.
13954 } else if (S
.getLangOpts().OpenCL
&& ResType
->isVectorType() &&
13955 ResType
->castAs
<VectorType
>()->getElementType()->isIntegerType()) {
13956 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13958 S
.Diag(OpLoc
, diag::err_typecheck_illegal_increment_decrement
)
13959 << ResType
<< int(IsInc
) << Op
->getSourceRange();
13962 // At this point, we know we have a real, complex or pointer type.
13963 // Now make sure the operand is a modifiable lvalue.
13964 if (CheckForModifiableLvalue(Op
, OpLoc
, S
))
13966 if (S
.getLangOpts().CPlusPlus20
&& ResType
.isVolatileQualified()) {
13967 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13968 // An operand with volatile-qualified type is deprecated
13969 S
.Diag(OpLoc
, diag::warn_deprecated_increment_decrement_volatile
)
13970 << IsInc
<< ResType
;
13972 // In C++, a prefix increment is the same type as the operand. Otherwise
13973 // (in C or with postfix), the increment is the unqualified type of the
13975 if (IsPrefix
&& S
.getLangOpts().CPlusPlus
) {
13977 OK
= Op
->getObjectKind();
13981 return ResType
.getUnqualifiedType();
13985 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13986 /// This routine allows us to typecheck complex/recursive expressions
13987 /// where the declaration is needed for type checking. We only need to
13988 /// handle cases when the expression references a function designator
13989 /// or is an lvalue. Here are some examples:
13991 /// - &*****f => f for f a function designator.
13993 /// - &s.zz[1].yy -> s, if zz is an array
13994 /// - *(x + 1) -> x, if x is an array
13995 /// - &"123"[2] -> 0
13996 /// - & __real__ x -> x
13998 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14000 static ValueDecl
*getPrimaryDecl(Expr
*E
) {
14001 switch (E
->getStmtClass()) {
14002 case Stmt::DeclRefExprClass
:
14003 return cast
<DeclRefExpr
>(E
)->getDecl();
14004 case Stmt::MemberExprClass
:
14005 // If this is an arrow operator, the address is an offset from
14006 // the base's value, so the object the base refers to is
14008 if (cast
<MemberExpr
>(E
)->isArrow())
14010 // Otherwise, the expression refers to a part of the base
14011 return getPrimaryDecl(cast
<MemberExpr
>(E
)->getBase());
14012 case Stmt::ArraySubscriptExprClass
: {
14013 // FIXME: This code shouldn't be necessary! We should catch the implicit
14014 // promotion of register arrays earlier.
14015 Expr
* Base
= cast
<ArraySubscriptExpr
>(E
)->getBase();
14016 if (ImplicitCastExpr
* ICE
= dyn_cast
<ImplicitCastExpr
>(Base
)) {
14017 if (ICE
->getSubExpr()->getType()->isArrayType())
14018 return getPrimaryDecl(ICE
->getSubExpr());
14022 case Stmt::UnaryOperatorClass
: {
14023 UnaryOperator
*UO
= cast
<UnaryOperator
>(E
);
14025 switch(UO
->getOpcode()) {
14029 return getPrimaryDecl(UO
->getSubExpr());
14034 case Stmt::ParenExprClass
:
14035 return getPrimaryDecl(cast
<ParenExpr
>(E
)->getSubExpr());
14036 case Stmt::ImplicitCastExprClass
:
14037 // If the result of an implicit cast is an l-value, we care about
14038 // the sub-expression; otherwise, the result here doesn't matter.
14039 return getPrimaryDecl(cast
<ImplicitCastExpr
>(E
)->getSubExpr());
14040 case Stmt::CXXUuidofExprClass
:
14041 return cast
<CXXUuidofExpr
>(E
)->getGuidDecl();
14050 AO_Vector_Element
= 1,
14051 AO_Property_Expansion
= 2,
14052 AO_Register_Variable
= 3,
14053 AO_Matrix_Element
= 4,
14057 /// Diagnose invalid operand for address of operations.
14059 /// \param Type The type of operand which cannot have its address taken.
14060 static void diagnoseAddressOfInvalidType(Sema
&S
, SourceLocation Loc
,
14061 Expr
*E
, unsigned Type
) {
14062 S
.Diag(Loc
, diag::err_typecheck_address_of
) << Type
<< E
->getSourceRange();
14065 bool Sema::CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc
,
14067 const CXXMethodDecl
*MD
) {
14068 const auto *DRE
= cast
<DeclRefExpr
>(Op
->IgnoreParens());
14071 return Diag(OpLoc
, diag::err_parens_pointer_member_function
)
14072 << Op
->getSourceRange();
14074 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14075 if (isa
<CXXDestructorDecl
>(MD
))
14076 return Diag(OpLoc
, diag::err_typecheck_addrof_dtor
)
14077 << DRE
->getSourceRange();
14079 if (DRE
->getQualifier())
14082 if (MD
->getParent()->getName().empty())
14083 return Diag(OpLoc
, diag::err_unqualified_pointer_member_function
)
14084 << DRE
->getSourceRange();
14086 SmallString
<32> Str
;
14087 StringRef Qual
= (MD
->getParent()->getName() + "::").toStringRef(Str
);
14088 return Diag(OpLoc
, diag::err_unqualified_pointer_member_function
)
14089 << DRE
->getSourceRange()
14090 << FixItHint::CreateInsertion(DRE
->getSourceRange().getBegin(), Qual
);
14093 QualType
Sema::CheckAddressOfOperand(ExprResult
&OrigOp
, SourceLocation OpLoc
) {
14094 if (const BuiltinType
*PTy
= OrigOp
.get()->getType()->getAsPlaceholderType()){
14095 if (PTy
->getKind() == BuiltinType::Overload
) {
14096 Expr
*E
= OrigOp
.get()->IgnoreParens();
14097 if (!isa
<OverloadExpr
>(E
)) {
14098 assert(cast
<UnaryOperator
>(E
)->getOpcode() == UO_AddrOf
);
14099 Diag(OpLoc
, diag::err_typecheck_invalid_lvalue_addrof_addrof_function
)
14100 << OrigOp
.get()->getSourceRange();
14104 OverloadExpr
*Ovl
= cast
<OverloadExpr
>(E
);
14105 if (isa
<UnresolvedMemberExpr
>(Ovl
))
14106 if (!ResolveSingleFunctionTemplateSpecialization(Ovl
)) {
14107 Diag(OpLoc
, diag::err_invalid_form_pointer_member_function
)
14108 << OrigOp
.get()->getSourceRange();
14112 return Context
.OverloadTy
;
14115 if (PTy
->getKind() == BuiltinType::UnknownAny
)
14116 return Context
.UnknownAnyTy
;
14118 if (PTy
->getKind() == BuiltinType::BoundMember
) {
14119 Diag(OpLoc
, diag::err_invalid_form_pointer_member_function
)
14120 << OrigOp
.get()->getSourceRange();
14124 OrigOp
= CheckPlaceholderExpr(OrigOp
.get());
14125 if (OrigOp
.isInvalid()) return QualType();
14128 if (OrigOp
.get()->isTypeDependent())
14129 return Context
.DependentTy
;
14131 assert(!OrigOp
.get()->hasPlaceholderType());
14133 // Make sure to ignore parentheses in subsequent checks
14134 Expr
*op
= OrigOp
.get()->IgnoreParens();
14136 // In OpenCL captures for blocks called as lambda functions
14137 // are located in the private address space. Blocks used in
14138 // enqueue_kernel can be located in a different address space
14139 // depending on a vendor implementation. Thus preventing
14140 // taking an address of the capture to avoid invalid AS casts.
14141 if (LangOpts
.OpenCL
) {
14142 auto* VarRef
= dyn_cast
<DeclRefExpr
>(op
);
14143 if (VarRef
&& VarRef
->refersToEnclosingVariableOrCapture()) {
14144 Diag(op
->getExprLoc(), diag::err_opencl_taking_address_capture
);
14149 if (getLangOpts().C99
) {
14150 // Implement C99-only parts of addressof rules.
14151 if (UnaryOperator
* uOp
= dyn_cast
<UnaryOperator
>(op
)) {
14152 if (uOp
->getOpcode() == UO_Deref
)
14153 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14154 // (assuming the deref expression is valid).
14155 return uOp
->getSubExpr()->getType();
14157 // Technically, there should be a check for array subscript
14158 // expressions here, but the result of one is always an lvalue anyway.
14160 ValueDecl
*dcl
= getPrimaryDecl(op
);
14162 if (auto *FD
= dyn_cast_or_null
<FunctionDecl
>(dcl
))
14163 if (!checkAddressOfFunctionIsAvailable(FD
, /*Complain=*/true,
14164 op
->getBeginLoc()))
14167 Expr::LValueClassification lval
= op
->ClassifyLValue(Context
);
14168 unsigned AddressOfError
= AO_No_Error
;
14170 if (lval
== Expr::LV_ClassTemporary
|| lval
== Expr::LV_ArrayTemporary
) {
14171 bool sfinae
= (bool)isSFINAEContext();
14172 Diag(OpLoc
, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14173 : diag::ext_typecheck_addrof_temporary
)
14174 << op
->getType() << op
->getSourceRange();
14177 // Materialize the temporary as an lvalue so that we can take its address.
14179 CreateMaterializeTemporaryExpr(op
->getType(), OrigOp
.get(), true);
14180 } else if (isa
<ObjCSelectorExpr
>(op
)) {
14181 return Context
.getPointerType(op
->getType());
14182 } else if (lval
== Expr::LV_MemberFunction
) {
14183 // If it's an instance method, make a member pointer.
14184 // The expression must have exactly the form &A::foo.
14186 // If the underlying expression isn't a decl ref, give up.
14187 if (!isa
<DeclRefExpr
>(op
)) {
14188 Diag(OpLoc
, diag::err_invalid_form_pointer_member_function
)
14189 << OrigOp
.get()->getSourceRange();
14192 DeclRefExpr
*DRE
= cast
<DeclRefExpr
>(op
);
14193 CXXMethodDecl
*MD
= cast
<CXXMethodDecl
>(DRE
->getDecl());
14195 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc
, OrigOp
.get(), MD
);
14197 QualType MPTy
= Context
.getMemberPointerType(
14198 op
->getType(), Context
.getTypeDeclType(MD
->getParent()).getTypePtr());
14200 if (getLangOpts().PointerAuthCalls
&& MD
->isVirtual() &&
14201 !isUnevaluatedContext() && !MPTy
->isDependentType()) {
14202 // When pointer authentication is enabled, argument and return types of
14203 // vitual member functions must be complete. This is because vitrual
14204 // member function pointers are implemented using virtual dispatch
14205 // thunks and the thunks cannot be emitted if the argument or return
14206 // types are incomplete.
14207 auto ReturnOrParamTypeIsIncomplete
= [&](QualType T
,
14208 SourceLocation DeclRefLoc
,
14209 SourceLocation RetArgTypeLoc
) {
14210 if (RequireCompleteType(DeclRefLoc
, T
, diag::err_incomplete_type
)) {
14212 diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret
);
14213 Diag(RetArgTypeLoc
,
14214 diag::note_ptrauth_virtual_function_incomplete_arg_ret_type
)
14220 QualType RetTy
= MD
->getReturnType();
14221 bool IsIncomplete
=
14222 !RetTy
->isVoidType() &&
14223 ReturnOrParamTypeIsIncomplete(
14224 RetTy
, OpLoc
, MD
->getReturnTypeSourceRange().getBegin());
14225 for (auto *PVD
: MD
->parameters())
14226 IsIncomplete
|= ReturnOrParamTypeIsIncomplete(PVD
->getType(), OpLoc
,
14227 PVD
->getBeginLoc());
14232 // Under the MS ABI, lock down the inheritance model now.
14233 if (Context
.getTargetInfo().getCXXABI().isMicrosoft())
14234 (void)isCompleteType(OpLoc
, MPTy
);
14236 } else if (lval
!= Expr::LV_Valid
&& lval
!= Expr::LV_IncompleteVoidType
) {
14238 // The operand must be either an l-value or a function designator
14239 if (!op
->getType()->isFunctionType()) {
14240 // Use a special diagnostic for loads from property references.
14241 if (isa
<PseudoObjectExpr
>(op
)) {
14242 AddressOfError
= AO_Property_Expansion
;
14244 Diag(OpLoc
, diag::err_typecheck_invalid_lvalue_addrof
)
14245 << op
->getType() << op
->getSourceRange();
14248 } else if (const auto *DRE
= dyn_cast
<DeclRefExpr
>(op
)) {
14249 if (const auto *MD
= dyn_cast_or_null
<CXXMethodDecl
>(DRE
->getDecl()))
14250 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc
, OrigOp
.get(), MD
);
14253 } else if (op
->getObjectKind() == OK_BitField
) { // C99 6.5.3.2p1
14254 // The operand cannot be a bit-field
14255 AddressOfError
= AO_Bit_Field
;
14256 } else if (op
->getObjectKind() == OK_VectorComponent
) {
14257 // The operand cannot be an element of a vector
14258 AddressOfError
= AO_Vector_Element
;
14259 } else if (op
->getObjectKind() == OK_MatrixComponent
) {
14260 // The operand cannot be an element of a matrix.
14261 AddressOfError
= AO_Matrix_Element
;
14262 } else if (dcl
) { // C99 6.5.3.2p1
14263 // We have an lvalue with a decl. Make sure the decl is not declared
14264 // with the register storage-class specifier.
14265 if (const VarDecl
*vd
= dyn_cast
<VarDecl
>(dcl
)) {
14266 // in C++ it is not error to take address of a register
14267 // variable (c++03 7.1.1P3)
14268 if (vd
->getStorageClass() == SC_Register
&&
14269 !getLangOpts().CPlusPlus
) {
14270 AddressOfError
= AO_Register_Variable
;
14272 } else if (isa
<MSPropertyDecl
>(dcl
)) {
14273 AddressOfError
= AO_Property_Expansion
;
14274 } else if (isa
<FunctionTemplateDecl
>(dcl
)) {
14275 return Context
.OverloadTy
;
14276 } else if (isa
<FieldDecl
>(dcl
) || isa
<IndirectFieldDecl
>(dcl
)) {
14277 // Okay: we can take the address of a field.
14278 // Could be a pointer to member, though, if there is an explicit
14279 // scope qualifier for the class.
14281 // [C++26] [expr.prim.id.general]
14282 // If an id-expression E denotes a non-static non-type member
14283 // of some class C [...] and if E is a qualified-id, E is
14284 // not the un-parenthesized operand of the unary & operator [...]
14285 // the id-expression is transformed into a class member access expression.
14286 if (isa
<DeclRefExpr
>(op
) && cast
<DeclRefExpr
>(op
)->getQualifier() &&
14287 !isa
<ParenExpr
>(OrigOp
.get())) {
14288 DeclContext
*Ctx
= dcl
->getDeclContext();
14289 if (Ctx
&& Ctx
->isRecord()) {
14290 if (dcl
->getType()->isReferenceType()) {
14292 diag::err_cannot_form_pointer_to_member_of_reference_type
)
14293 << dcl
->getDeclName() << dcl
->getType();
14297 while (cast
<RecordDecl
>(Ctx
)->isAnonymousStructOrUnion())
14298 Ctx
= Ctx
->getParent();
14300 QualType MPTy
= Context
.getMemberPointerType(
14302 Context
.getTypeDeclType(cast
<RecordDecl
>(Ctx
)).getTypePtr());
14303 // Under the MS ABI, lock down the inheritance model now.
14304 if (Context
.getTargetInfo().getCXXABI().isMicrosoft())
14305 (void)isCompleteType(OpLoc
, MPTy
);
14309 } else if (!isa
<FunctionDecl
, NonTypeTemplateParmDecl
, BindingDecl
,
14310 MSGuidDecl
, UnnamedGlobalConstantDecl
>(dcl
))
14311 llvm_unreachable("Unknown/unexpected decl type");
14314 if (AddressOfError
!= AO_No_Error
) {
14315 diagnoseAddressOfInvalidType(*this, OpLoc
, op
, AddressOfError
);
14319 if (lval
== Expr::LV_IncompleteVoidType
) {
14320 // Taking the address of a void variable is technically illegal, but we
14321 // allow it in cases which are otherwise valid.
14322 // Example: "extern void x; void* y = &x;".
14323 Diag(OpLoc
, diag::ext_typecheck_addrof_void
) << op
->getSourceRange();
14326 // If the operand has type "type", the result has type "pointer to type".
14327 if (op
->getType()->isObjCObjectType())
14328 return Context
.getObjCObjectPointerType(op
->getType());
14330 // Cannot take the address of WebAssembly references or tables.
14331 if (Context
.getTargetInfo().getTriple().isWasm()) {
14332 QualType OpTy
= op
->getType();
14333 if (OpTy
.isWebAssemblyReferenceType()) {
14334 Diag(OpLoc
, diag::err_wasm_ca_reference
)
14335 << 1 << OrigOp
.get()->getSourceRange();
14338 if (OpTy
->isWebAssemblyTableType()) {
14339 Diag(OpLoc
, diag::err_wasm_table_pr
)
14340 << 1 << OrigOp
.get()->getSourceRange();
14345 CheckAddressOfPackedMember(op
);
14347 return Context
.getPointerType(op
->getType());
14350 static void RecordModifiableNonNullParam(Sema
&S
, const Expr
*Exp
) {
14351 const DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(Exp
);
14354 const Decl
*D
= DRE
->getDecl();
14357 const ParmVarDecl
*Param
= dyn_cast
<ParmVarDecl
>(D
);
14360 if (const FunctionDecl
* FD
= dyn_cast
<FunctionDecl
>(Param
->getDeclContext()))
14361 if (!FD
->hasAttr
<NonNullAttr
>() && !Param
->hasAttr
<NonNullAttr
>())
14363 if (FunctionScopeInfo
*FD
= S
.getCurFunction())
14364 FD
->ModifiedNonNullParams
.insert(Param
);
14367 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14368 static QualType
CheckIndirectionOperand(Sema
&S
, Expr
*Op
, ExprValueKind
&VK
,
14369 SourceLocation OpLoc
,
14370 bool IsAfterAmp
= false) {
14371 ExprResult ConvResult
= S
.UsualUnaryConversions(Op
);
14372 if (ConvResult
.isInvalid())
14374 Op
= ConvResult
.get();
14375 QualType OpTy
= Op
->getType();
14378 if (isa
<CXXReinterpretCastExpr
>(Op
)) {
14379 QualType OpOrigType
= Op
->IgnoreParenCasts()->getType();
14380 S
.CheckCompatibleReinterpretCast(OpOrigType
, OpTy
, /*IsDereference*/true,
14381 Op
->getSourceRange());
14384 if (const PointerType
*PT
= OpTy
->getAs
<PointerType
>())
14386 Result
= PT
->getPointeeType();
14388 else if (const ObjCObjectPointerType
*OPT
=
14389 OpTy
->getAs
<ObjCObjectPointerType
>())
14390 Result
= OPT
->getPointeeType();
14392 ExprResult PR
= S
.CheckPlaceholderExpr(Op
);
14393 if (PR
.isInvalid()) return QualType();
14394 if (PR
.get() != Op
)
14395 return CheckIndirectionOperand(S
, PR
.get(), VK
, OpLoc
);
14398 if (Result
.isNull()) {
14399 S
.Diag(OpLoc
, diag::err_typecheck_indirection_requires_pointer
)
14400 << OpTy
<< Op
->getSourceRange();
14404 if (Result
->isVoidType()) {
14405 // C++ [expr.unary.op]p1:
14406 // [...] the expression to which [the unary * operator] is applied shall
14407 // be a pointer to an object type, or a pointer to a function type
14408 LangOptions LO
= S
.getLangOpts();
14410 S
.Diag(OpLoc
, diag::err_typecheck_indirection_through_void_pointer_cpp
)
14411 << OpTy
<< Op
->getSourceRange();
14412 else if (!(LO
.C99
&& IsAfterAmp
) && !S
.isUnevaluatedContext())
14413 S
.Diag(OpLoc
, diag::ext_typecheck_indirection_through_void_pointer
)
14414 << OpTy
<< Op
->getSourceRange();
14417 // Dereferences are usually l-values...
14420 // ...except that certain expressions are never l-values in C.
14421 if (!S
.getLangOpts().CPlusPlus
&& Result
.isCForbiddenLValueType())
14427 BinaryOperatorKind
Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind
) {
14428 BinaryOperatorKind Opc
;
14430 default: llvm_unreachable("Unknown binop!");
14431 case tok::periodstar
: Opc
= BO_PtrMemD
; break;
14432 case tok::arrowstar
: Opc
= BO_PtrMemI
; break;
14433 case tok::star
: Opc
= BO_Mul
; break;
14434 case tok::slash
: Opc
= BO_Div
; break;
14435 case tok::percent
: Opc
= BO_Rem
; break;
14436 case tok::plus
: Opc
= BO_Add
; break;
14437 case tok::minus
: Opc
= BO_Sub
; break;
14438 case tok::lessless
: Opc
= BO_Shl
; break;
14439 case tok::greatergreater
: Opc
= BO_Shr
; break;
14440 case tok::lessequal
: Opc
= BO_LE
; break;
14441 case tok::less
: Opc
= BO_LT
; break;
14442 case tok::greaterequal
: Opc
= BO_GE
; break;
14443 case tok::greater
: Opc
= BO_GT
; break;
14444 case tok::exclaimequal
: Opc
= BO_NE
; break;
14445 case tok::equalequal
: Opc
= BO_EQ
; break;
14446 case tok::spaceship
: Opc
= BO_Cmp
; break;
14447 case tok::amp
: Opc
= BO_And
; break;
14448 case tok::caret
: Opc
= BO_Xor
; break;
14449 case tok::pipe
: Opc
= BO_Or
; break;
14450 case tok::ampamp
: Opc
= BO_LAnd
; break;
14451 case tok::pipepipe
: Opc
= BO_LOr
; break;
14452 case tok::equal
: Opc
= BO_Assign
; break;
14453 case tok::starequal
: Opc
= BO_MulAssign
; break;
14454 case tok::slashequal
: Opc
= BO_DivAssign
; break;
14455 case tok::percentequal
: Opc
= BO_RemAssign
; break;
14456 case tok::plusequal
: Opc
= BO_AddAssign
; break;
14457 case tok::minusequal
: Opc
= BO_SubAssign
; break;
14458 case tok::lesslessequal
: Opc
= BO_ShlAssign
; break;
14459 case tok::greatergreaterequal
: Opc
= BO_ShrAssign
; break;
14460 case tok::ampequal
: Opc
= BO_AndAssign
; break;
14461 case tok::caretequal
: Opc
= BO_XorAssign
; break;
14462 case tok::pipeequal
: Opc
= BO_OrAssign
; break;
14463 case tok::comma
: Opc
= BO_Comma
; break;
14468 static inline UnaryOperatorKind
ConvertTokenKindToUnaryOpcode(
14469 tok::TokenKind Kind
) {
14470 UnaryOperatorKind Opc
;
14472 default: llvm_unreachable("Unknown unary op!");
14473 case tok::plusplus
: Opc
= UO_PreInc
; break;
14474 case tok::minusminus
: Opc
= UO_PreDec
; break;
14475 case tok::amp
: Opc
= UO_AddrOf
; break;
14476 case tok::star
: Opc
= UO_Deref
; break;
14477 case tok::plus
: Opc
= UO_Plus
; break;
14478 case tok::minus
: Opc
= UO_Minus
; break;
14479 case tok::tilde
: Opc
= UO_Not
; break;
14480 case tok::exclaim
: Opc
= UO_LNot
; break;
14481 case tok::kw___real
: Opc
= UO_Real
; break;
14482 case tok::kw___imag
: Opc
= UO_Imag
; break;
14483 case tok::kw___extension__
: Opc
= UO_Extension
; break;
14489 Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl
*SelfAssigned
) {
14490 // Explore the case for adding 'this->' to the LHS of a self assignment, very
14491 // common for setters.
14494 // -void setX(int X) { X = X; }
14495 // +void setX(int X) { this->X = X; }
14498 // Only consider parameters for self assignment fixes.
14499 if (!isa
<ParmVarDecl
>(SelfAssigned
))
14501 const auto *Method
=
14502 dyn_cast_or_null
<CXXMethodDecl
>(getCurFunctionDecl(true));
14506 const CXXRecordDecl
*Parent
= Method
->getParent();
14507 // In theory this is fixable if the lambda explicitly captures this, but
14508 // that's added complexity that's rarely going to be used.
14509 if (Parent
->isLambda())
14512 // FIXME: Use an actual Lookup operation instead of just traversing fields
14513 // in order to get base class fields.
14515 llvm::find_if(Parent
->fields(),
14516 [Name(SelfAssigned
->getDeclName())](const FieldDecl
*F
) {
14517 return F
->getDeclName() == Name
;
14519 return (Field
!= Parent
->field_end()) ? *Field
: nullptr;
14522 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14523 /// This warning suppressed in the event of macro expansions.
14524 static void DiagnoseSelfAssignment(Sema
&S
, Expr
*LHSExpr
, Expr
*RHSExpr
,
14525 SourceLocation OpLoc
, bool IsBuiltin
) {
14526 if (S
.inTemplateInstantiation())
14528 if (S
.isUnevaluatedContext())
14530 if (OpLoc
.isInvalid() || OpLoc
.isMacroID())
14532 LHSExpr
= LHSExpr
->IgnoreParenImpCasts();
14533 RHSExpr
= RHSExpr
->IgnoreParenImpCasts();
14534 const DeclRefExpr
*LHSDeclRef
= dyn_cast
<DeclRefExpr
>(LHSExpr
);
14535 const DeclRefExpr
*RHSDeclRef
= dyn_cast
<DeclRefExpr
>(RHSExpr
);
14536 if (!LHSDeclRef
|| !RHSDeclRef
||
14537 LHSDeclRef
->getLocation().isMacroID() ||
14538 RHSDeclRef
->getLocation().isMacroID())
14540 const ValueDecl
*LHSDecl
=
14541 cast
<ValueDecl
>(LHSDeclRef
->getDecl()->getCanonicalDecl());
14542 const ValueDecl
*RHSDecl
=
14543 cast
<ValueDecl
>(RHSDeclRef
->getDecl()->getCanonicalDecl());
14544 if (LHSDecl
!= RHSDecl
)
14546 if (LHSDecl
->getType().isVolatileQualified())
14548 if (const ReferenceType
*RefTy
= LHSDecl
->getType()->getAs
<ReferenceType
>())
14549 if (RefTy
->getPointeeType().isVolatileQualified())
14552 auto Diag
= S
.Diag(OpLoc
, IsBuiltin
? diag::warn_self_assignment_builtin
14553 : diag::warn_self_assignment_overloaded
)
14554 << LHSDeclRef
->getType() << LHSExpr
->getSourceRange()
14555 << RHSExpr
->getSourceRange();
14556 if (const FieldDecl
*SelfAssignField
=
14557 S
.getSelfAssignmentClassMemberCandidate(RHSDecl
))
14558 Diag
<< 1 << SelfAssignField
14559 << FixItHint::CreateInsertion(LHSDeclRef
->getBeginLoc(), "this->");
14564 /// Check if a bitwise-& is performed on an Objective-C pointer. This
14565 /// is usually indicative of introspection within the Objective-C pointer.
14566 static void checkObjCPointerIntrospection(Sema
&S
, ExprResult
&L
, ExprResult
&R
,
14567 SourceLocation OpLoc
) {
14568 if (!S
.getLangOpts().ObjC
)
14571 const Expr
*ObjCPointerExpr
= nullptr, *OtherExpr
= nullptr;
14572 const Expr
*LHS
= L
.get();
14573 const Expr
*RHS
= R
.get();
14575 if (LHS
->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14576 ObjCPointerExpr
= LHS
;
14579 else if (RHS
->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14580 ObjCPointerExpr
= RHS
;
14584 // This warning is deliberately made very specific to reduce false
14585 // positives with logic that uses '&' for hashing. This logic mainly
14586 // looks for code trying to introspect into tagged pointers, which
14587 // code should generally never do.
14588 if (ObjCPointerExpr
&& isa
<IntegerLiteral
>(OtherExpr
->IgnoreParenCasts())) {
14589 unsigned Diag
= diag::warn_objc_pointer_masking
;
14590 // Determine if we are introspecting the result of performSelectorXXX.
14591 const Expr
*Ex
= ObjCPointerExpr
->IgnoreParenCasts();
14592 // Special case messages to -performSelector and friends, which
14593 // can return non-pointer values boxed in a pointer value.
14594 // Some clients may wish to silence warnings in this subcase.
14595 if (const ObjCMessageExpr
*ME
= dyn_cast
<ObjCMessageExpr
>(Ex
)) {
14596 Selector S
= ME
->getSelector();
14597 StringRef SelArg0
= S
.getNameForSlot(0);
14598 if (SelArg0
.starts_with("performSelector"))
14599 Diag
= diag::warn_objc_pointer_masking_performSelector
;
14602 S
.Diag(OpLoc
, Diag
)
14603 << ObjCPointerExpr
->getSourceRange();
14607 static NamedDecl
*getDeclFromExpr(Expr
*E
) {
14610 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(E
))
14611 return DRE
->getDecl();
14612 if (auto *ME
= dyn_cast
<MemberExpr
>(E
))
14613 return ME
->getMemberDecl();
14614 if (auto *IRE
= dyn_cast
<ObjCIvarRefExpr
>(E
))
14615 return IRE
->getDecl();
14619 // This helper function promotes a binary operator's operands (which are of a
14620 // half vector type) to a vector of floats and then truncates the result to
14621 // a vector of either half or short.
14622 static ExprResult
convertHalfVecBinOp(Sema
&S
, ExprResult LHS
, ExprResult RHS
,
14623 BinaryOperatorKind Opc
, QualType ResultTy
,
14624 ExprValueKind VK
, ExprObjectKind OK
,
14625 bool IsCompAssign
, SourceLocation OpLoc
,
14626 FPOptionsOverride FPFeatures
) {
14627 auto &Context
= S
.getASTContext();
14628 assert((isVector(ResultTy
, Context
.HalfTy
) ||
14629 isVector(ResultTy
, Context
.ShortTy
)) &&
14630 "Result must be a vector of half or short");
14631 assert(isVector(LHS
.get()->getType(), Context
.HalfTy
) &&
14632 isVector(RHS
.get()->getType(), Context
.HalfTy
) &&
14633 "both operands expected to be a half vector");
14635 RHS
= convertVector(RHS
.get(), Context
.FloatTy
, S
);
14636 QualType BinOpResTy
= RHS
.get()->getType();
14638 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14639 // change BinOpResTy to a vector of ints.
14640 if (isVector(ResultTy
, Context
.ShortTy
))
14641 BinOpResTy
= S
.GetSignedVectorType(BinOpResTy
);
14644 return CompoundAssignOperator::Create(Context
, LHS
.get(), RHS
.get(), Opc
,
14645 ResultTy
, VK
, OK
, OpLoc
, FPFeatures
,
14646 BinOpResTy
, BinOpResTy
);
14648 LHS
= convertVector(LHS
.get(), Context
.FloatTy
, S
);
14649 auto *BO
= BinaryOperator::Create(Context
, LHS
.get(), RHS
.get(), Opc
,
14650 BinOpResTy
, VK
, OK
, OpLoc
, FPFeatures
);
14651 return convertVector(BO
, ResultTy
->castAs
<VectorType
>()->getElementType(), S
);
14654 static std::pair
<ExprResult
, ExprResult
>
14655 CorrectDelayedTyposInBinOp(Sema
&S
, BinaryOperatorKind Opc
, Expr
*LHSExpr
,
14657 ExprResult LHS
= LHSExpr
, RHS
= RHSExpr
;
14658 if (!S
.Context
.isDependenceAllowed()) {
14659 // C cannot handle TypoExpr nodes on either side of a binop because it
14660 // doesn't handle dependent types properly, so make sure any TypoExprs have
14661 // been dealt with before checking the operands.
14662 LHS
= S
.CorrectDelayedTyposInExpr(LHS
);
14663 RHS
= S
.CorrectDelayedTyposInExpr(
14664 RHS
, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14665 [Opc
, LHS
](Expr
*E
) {
14666 if (Opc
!= BO_Assign
)
14667 return ExprResult(E
);
14668 // Avoid correcting the RHS to the same Expr as the LHS.
14669 Decl
*D
= getDeclFromExpr(E
);
14670 return (D
&& D
== getDeclFromExpr(LHS
.get())) ? ExprError() : E
;
14673 return std::make_pair(LHS
, RHS
);
14676 /// Returns true if conversion between vectors of halfs and vectors of floats
14678 static bool needsConversionOfHalfVec(bool OpRequiresConversion
, ASTContext
&Ctx
,
14679 Expr
*E0
, Expr
*E1
= nullptr) {
14680 if (!OpRequiresConversion
|| Ctx
.getLangOpts().NativeHalfType
||
14681 Ctx
.getTargetInfo().useFP16ConversionIntrinsics())
14684 auto HasVectorOfHalfType
= [&Ctx
](Expr
*E
) {
14685 QualType Ty
= E
->IgnoreImplicit()->getType();
14687 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14688 // to vectors of floats. Although the element type of the vectors is __fp16,
14689 // the vectors shouldn't be treated as storage-only types. See the
14690 // discussion here: https://reviews.llvm.org/rG825235c140e7
14691 if (const VectorType
*VT
= Ty
->getAs
<VectorType
>()) {
14692 if (VT
->getVectorKind() == VectorKind::Neon
)
14694 return VT
->getElementType().getCanonicalType() == Ctx
.HalfTy
;
14699 return HasVectorOfHalfType(E0
) && (!E1
|| HasVectorOfHalfType(E1
));
14702 ExprResult
Sema::CreateBuiltinBinOp(SourceLocation OpLoc
,
14703 BinaryOperatorKind Opc
,
14704 Expr
*LHSExpr
, Expr
*RHSExpr
) {
14705 if (getLangOpts().CPlusPlus11
&& isa
<InitListExpr
>(RHSExpr
)) {
14706 // The syntax only allows initializer lists on the RHS of assignment,
14707 // so we don't need to worry about accepting invalid code for
14708 // non-assignment operators.
14710 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14711 // of x = {} is x = T().
14712 InitializationKind Kind
= InitializationKind::CreateDirectList(
14713 RHSExpr
->getBeginLoc(), RHSExpr
->getBeginLoc(), RHSExpr
->getEndLoc());
14714 InitializedEntity Entity
=
14715 InitializedEntity::InitializeTemporary(LHSExpr
->getType());
14716 InitializationSequence
InitSeq(*this, Entity
, Kind
, RHSExpr
);
14717 ExprResult Init
= InitSeq
.Perform(*this, Entity
, Kind
, RHSExpr
);
14718 if (Init
.isInvalid())
14720 RHSExpr
= Init
.get();
14723 ExprResult LHS
= LHSExpr
, RHS
= RHSExpr
;
14724 QualType ResultTy
; // Result type of the binary operator.
14725 // The following two variables are used for compound assignment operators
14726 QualType CompLHSTy
; // Type of LHS after promotions for computation
14727 QualType CompResultTy
; // Type of computation result
14728 ExprValueKind VK
= VK_PRValue
;
14729 ExprObjectKind OK
= OK_Ordinary
;
14730 bool ConvertHalfVec
= false;
14732 std::tie(LHS
, RHS
) = CorrectDelayedTyposInBinOp(*this, Opc
, LHSExpr
, RHSExpr
);
14733 if (!LHS
.isUsable() || !RHS
.isUsable())
14734 return ExprError();
14736 if (getLangOpts().OpenCL
) {
14737 QualType LHSTy
= LHSExpr
->getType();
14738 QualType RHSTy
= RHSExpr
->getType();
14739 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14740 // the ATOMIC_VAR_INIT macro.
14741 if (LHSTy
->isAtomicType() || RHSTy
->isAtomicType()) {
14742 SourceRange
SR(LHSExpr
->getBeginLoc(), RHSExpr
->getEndLoc());
14743 if (BO_Assign
== Opc
)
14744 Diag(OpLoc
, diag::err_opencl_atomic_init
) << 0 << SR
;
14746 ResultTy
= InvalidOperands(OpLoc
, LHS
, RHS
);
14747 return ExprError();
14750 // OpenCL special types - image, sampler, pipe, and blocks are to be used
14751 // only with a builtin functions and therefore should be disallowed here.
14752 if (LHSTy
->isImageType() || RHSTy
->isImageType() ||
14753 LHSTy
->isSamplerT() || RHSTy
->isSamplerT() ||
14754 LHSTy
->isPipeType() || RHSTy
->isPipeType() ||
14755 LHSTy
->isBlockPointerType() || RHSTy
->isBlockPointerType()) {
14756 ResultTy
= InvalidOperands(OpLoc
, LHS
, RHS
);
14757 return ExprError();
14761 checkTypeSupport(LHSExpr
->getType(), OpLoc
, /*ValueDecl*/ nullptr);
14762 checkTypeSupport(RHSExpr
->getType(), OpLoc
, /*ValueDecl*/ nullptr);
14766 ResultTy
= CheckAssignmentOperands(LHS
.get(), RHS
, OpLoc
, QualType(), Opc
);
14767 if (getLangOpts().CPlusPlus
&&
14768 LHS
.get()->getObjectKind() != OK_ObjCProperty
) {
14769 VK
= LHS
.get()->getValueKind();
14770 OK
= LHS
.get()->getObjectKind();
14772 if (!ResultTy
.isNull()) {
14773 DiagnoseSelfAssignment(*this, LHS
.get(), RHS
.get(), OpLoc
, true);
14774 DiagnoseSelfMove(LHS
.get(), RHS
.get(), OpLoc
);
14776 // Avoid copying a block to the heap if the block is assigned to a local
14777 // auto variable that is declared in the same scope as the block. This
14778 // optimization is unsafe if the local variable is declared in an outer
14779 // scope. For example:
14785 // // It is unsafe to invoke the block here if it wasn't copied to the
14789 if (auto *BE
= dyn_cast
<BlockExpr
>(RHS
.get()->IgnoreParens()))
14790 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(LHS
.get()->IgnoreParens()))
14791 if (auto *VD
= dyn_cast
<VarDecl
>(DRE
->getDecl()))
14792 if (VD
->hasLocalStorage() && getCurScope()->isDeclScope(VD
))
14793 BE
->getBlockDecl()->setCanAvoidCopyToHeap();
14795 if (LHS
.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
14796 checkNonTrivialCUnion(LHS
.get()->getType(), LHS
.get()->getExprLoc(),
14797 NTCUC_Assignment
, NTCUK_Copy
);
14799 RecordModifiableNonNullParam(*this, LHS
.get());
14803 ResultTy
= CheckPointerToMemberOperands(LHS
, RHS
, VK
, OpLoc
,
14804 Opc
== BO_PtrMemI
);
14808 ConvertHalfVec
= true;
14809 ResultTy
= CheckMultiplyDivideOperands(LHS
, RHS
, OpLoc
, false,
14813 ResultTy
= CheckRemainderOperands(LHS
, RHS
, OpLoc
);
14816 ConvertHalfVec
= true;
14817 ResultTy
= CheckAdditionOperands(LHS
, RHS
, OpLoc
, Opc
);
14820 ConvertHalfVec
= true;
14821 ResultTy
= CheckSubtractionOperands(LHS
, RHS
, OpLoc
);
14825 ResultTy
= CheckShiftOperands(LHS
, RHS
, OpLoc
, Opc
);
14831 ConvertHalfVec
= true;
14832 ResultTy
= CheckCompareOperands(LHS
, RHS
, OpLoc
, Opc
);
14834 if (const auto *BI
= dyn_cast
<BinaryOperator
>(LHSExpr
);
14835 BI
&& BI
->isComparisonOp())
14836 Diag(OpLoc
, diag::warn_consecutive_comparison
);
14841 ConvertHalfVec
= true;
14842 ResultTy
= CheckCompareOperands(LHS
, RHS
, OpLoc
, Opc
);
14845 ConvertHalfVec
= true;
14846 ResultTy
= CheckCompareOperands(LHS
, RHS
, OpLoc
, Opc
);
14847 assert(ResultTy
.isNull() || ResultTy
->getAsCXXRecordDecl());
14850 checkObjCPointerIntrospection(*this, LHS
, RHS
, OpLoc
);
14854 ResultTy
= CheckBitwiseOperands(LHS
, RHS
, OpLoc
, Opc
);
14858 ConvertHalfVec
= true;
14859 ResultTy
= CheckLogicalOperands(LHS
, RHS
, OpLoc
, Opc
);
14863 ConvertHalfVec
= true;
14864 CompResultTy
= CheckMultiplyDivideOperands(LHS
, RHS
, OpLoc
, true,
14865 Opc
== BO_DivAssign
);
14866 CompLHSTy
= CompResultTy
;
14867 if (!CompResultTy
.isNull() && !LHS
.isInvalid() && !RHS
.isInvalid())
14869 CheckAssignmentOperands(LHS
.get(), RHS
, OpLoc
, CompResultTy
, Opc
);
14872 CompResultTy
= CheckRemainderOperands(LHS
, RHS
, OpLoc
, true);
14873 CompLHSTy
= CompResultTy
;
14874 if (!CompResultTy
.isNull() && !LHS
.isInvalid() && !RHS
.isInvalid())
14876 CheckAssignmentOperands(LHS
.get(), RHS
, OpLoc
, CompResultTy
, Opc
);
14879 ConvertHalfVec
= true;
14880 CompResultTy
= CheckAdditionOperands(LHS
, RHS
, OpLoc
, Opc
, &CompLHSTy
);
14881 if (!CompResultTy
.isNull() && !LHS
.isInvalid() && !RHS
.isInvalid())
14883 CheckAssignmentOperands(LHS
.get(), RHS
, OpLoc
, CompResultTy
, Opc
);
14886 ConvertHalfVec
= true;
14887 CompResultTy
= CheckSubtractionOperands(LHS
, RHS
, OpLoc
, &CompLHSTy
);
14888 if (!CompResultTy
.isNull() && !LHS
.isInvalid() && !RHS
.isInvalid())
14890 CheckAssignmentOperands(LHS
.get(), RHS
, OpLoc
, CompResultTy
, Opc
);
14894 CompResultTy
= CheckShiftOperands(LHS
, RHS
, OpLoc
, Opc
, true);
14895 CompLHSTy
= CompResultTy
;
14896 if (!CompResultTy
.isNull() && !LHS
.isInvalid() && !RHS
.isInvalid())
14898 CheckAssignmentOperands(LHS
.get(), RHS
, OpLoc
, CompResultTy
, Opc
);
14901 case BO_OrAssign
: // fallthrough
14902 DiagnoseSelfAssignment(*this, LHS
.get(), RHS
.get(), OpLoc
, true);
14905 CompResultTy
= CheckBitwiseOperands(LHS
, RHS
, OpLoc
, Opc
);
14906 CompLHSTy
= CompResultTy
;
14907 if (!CompResultTy
.isNull() && !LHS
.isInvalid() && !RHS
.isInvalid())
14909 CheckAssignmentOperands(LHS
.get(), RHS
, OpLoc
, CompResultTy
, Opc
);
14912 ResultTy
= CheckCommaOperands(*this, LHS
, RHS
, OpLoc
);
14913 if (getLangOpts().CPlusPlus
&& !RHS
.isInvalid()) {
14914 VK
= RHS
.get()->getValueKind();
14915 OK
= RHS
.get()->getObjectKind();
14919 if (ResultTy
.isNull() || LHS
.isInvalid() || RHS
.isInvalid())
14920 return ExprError();
14922 // Some of the binary operations require promoting operands of half vector to
14923 // float vectors and truncating the result back to half vector. For now, we do
14924 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14927 (Opc
== BO_Comma
|| isVector(RHS
.get()->getType(), Context
.HalfTy
) ==
14928 isVector(LHS
.get()->getType(), Context
.HalfTy
)) &&
14929 "both sides are half vectors or neither sides are");
14931 needsConversionOfHalfVec(ConvertHalfVec
, Context
, LHS
.get(), RHS
.get());
14933 // Check for array bounds violations for both sides of the BinaryOperator
14934 CheckArrayAccess(LHS
.get());
14935 CheckArrayAccess(RHS
.get());
14937 if (const ObjCIsaExpr
*OISA
= dyn_cast
<ObjCIsaExpr
>(LHS
.get()->IgnoreParenCasts())) {
14938 NamedDecl
*ObjectSetClass
= LookupSingleName(TUScope
,
14939 &Context
.Idents
.get("object_setClass"),
14940 SourceLocation(), LookupOrdinaryName
);
14941 if (ObjectSetClass
&& isa
<ObjCIsaExpr
>(LHS
.get())) {
14942 SourceLocation RHSLocEnd
= getLocForEndOfToken(RHS
.get()->getEndLoc());
14943 Diag(LHS
.get()->getExprLoc(), diag::warn_objc_isa_assign
)
14944 << FixItHint::CreateInsertion(LHS
.get()->getBeginLoc(),
14945 "object_setClass(")
14946 << FixItHint::CreateReplacement(SourceRange(OISA
->getOpLoc(), OpLoc
),
14948 << FixItHint::CreateInsertion(RHSLocEnd
, ")");
14951 Diag(LHS
.get()->getExprLoc(), diag::warn_objc_isa_assign
);
14953 else if (const ObjCIvarRefExpr
*OIRE
=
14954 dyn_cast
<ObjCIvarRefExpr
>(LHS
.get()->IgnoreParenCasts()))
14955 DiagnoseDirectIsaAccess(*this, OIRE
, OpLoc
, RHS
.get());
14957 // Opc is not a compound assignment if CompResultTy is null.
14958 if (CompResultTy
.isNull()) {
14959 if (ConvertHalfVec
)
14960 return convertHalfVecBinOp(*this, LHS
, RHS
, Opc
, ResultTy
, VK
, OK
, false,
14961 OpLoc
, CurFPFeatureOverrides());
14962 return BinaryOperator::Create(Context
, LHS
.get(), RHS
.get(), Opc
, ResultTy
,
14963 VK
, OK
, OpLoc
, CurFPFeatureOverrides());
14966 // Handle compound assignments.
14967 if (getLangOpts().CPlusPlus
&& LHS
.get()->getObjectKind() !=
14970 OK
= LHS
.get()->getObjectKind();
14973 // The LHS is not converted to the result type for fixed-point compound
14974 // assignment as the common type is computed on demand. Reset the CompLHSTy
14975 // to the LHS type we would have gotten after unary conversions.
14976 if (CompResultTy
->isFixedPointType())
14977 CompLHSTy
= UsualUnaryConversions(LHS
.get()).get()->getType();
14979 if (ConvertHalfVec
)
14980 return convertHalfVecBinOp(*this, LHS
, RHS
, Opc
, ResultTy
, VK
, OK
, true,
14981 OpLoc
, CurFPFeatureOverrides());
14983 return CompoundAssignOperator::Create(
14984 Context
, LHS
.get(), RHS
.get(), Opc
, ResultTy
, VK
, OK
, OpLoc
,
14985 CurFPFeatureOverrides(), CompLHSTy
, CompResultTy
);
14988 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14989 /// operators are mixed in a way that suggests that the programmer forgot that
14990 /// comparison operators have higher precedence. The most typical example of
14991 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14992 static void DiagnoseBitwisePrecedence(Sema
&Self
, BinaryOperatorKind Opc
,
14993 SourceLocation OpLoc
, Expr
*LHSExpr
,
14995 BinaryOperator
*LHSBO
= dyn_cast
<BinaryOperator
>(LHSExpr
);
14996 BinaryOperator
*RHSBO
= dyn_cast
<BinaryOperator
>(RHSExpr
);
14998 // Check that one of the sides is a comparison operator and the other isn't.
14999 bool isLeftComp
= LHSBO
&& LHSBO
->isComparisonOp();
15000 bool isRightComp
= RHSBO
&& RHSBO
->isComparisonOp();
15001 if (isLeftComp
== isRightComp
)
15004 // Bitwise operations are sometimes used as eager logical ops.
15005 // Don't diagnose this.
15006 bool isLeftBitwise
= LHSBO
&& LHSBO
->isBitwiseOp();
15007 bool isRightBitwise
= RHSBO
&& RHSBO
->isBitwiseOp();
15008 if (isLeftBitwise
|| isRightBitwise
)
15011 SourceRange DiagRange
= isLeftComp
15012 ? SourceRange(LHSExpr
->getBeginLoc(), OpLoc
)
15013 : SourceRange(OpLoc
, RHSExpr
->getEndLoc());
15014 StringRef OpStr
= isLeftComp
? LHSBO
->getOpcodeStr() : RHSBO
->getOpcodeStr();
15015 SourceRange ParensRange
=
15017 ? SourceRange(LHSBO
->getRHS()->getBeginLoc(), RHSExpr
->getEndLoc())
15018 : SourceRange(LHSExpr
->getBeginLoc(), RHSBO
->getLHS()->getEndLoc());
15020 Self
.Diag(OpLoc
, diag::warn_precedence_bitwise_rel
)
15021 << DiagRange
<< BinaryOperator::getOpcodeStr(Opc
) << OpStr
;
15022 SuggestParentheses(Self
, OpLoc
,
15023 Self
.PDiag(diag::note_precedence_silence
) << OpStr
,
15024 (isLeftComp
? LHSExpr
: RHSExpr
)->getSourceRange());
15025 SuggestParentheses(Self
, OpLoc
,
15026 Self
.PDiag(diag::note_precedence_bitwise_first
)
15027 << BinaryOperator::getOpcodeStr(Opc
),
15031 /// It accepts a '&&' expr that is inside a '||' one.
15032 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15033 /// in parentheses.
15035 EmitDiagnosticForLogicalAndInLogicalOr(Sema
&Self
, SourceLocation OpLoc
,
15036 BinaryOperator
*Bop
) {
15037 assert(Bop
->getOpcode() == BO_LAnd
);
15038 Self
.Diag(Bop
->getOperatorLoc(), diag::warn_logical_and_in_logical_or
)
15039 << Bop
->getSourceRange() << OpLoc
;
15040 SuggestParentheses(Self
, Bop
->getOperatorLoc(),
15041 Self
.PDiag(diag::note_precedence_silence
)
15042 << Bop
->getOpcodeStr(),
15043 Bop
->getSourceRange());
15046 /// Look for '&&' in the left hand of a '||' expr.
15047 static void DiagnoseLogicalAndInLogicalOrLHS(Sema
&S
, SourceLocation OpLoc
,
15048 Expr
*LHSExpr
, Expr
*RHSExpr
) {
15049 if (BinaryOperator
*Bop
= dyn_cast
<BinaryOperator
>(LHSExpr
)) {
15050 if (Bop
->getOpcode() == BO_LAnd
) {
15051 // If it's "string_literal && a || b" don't warn since the precedence
15053 if (!isa
<StringLiteral
>(Bop
->getLHS()->IgnoreParenImpCasts()))
15054 return EmitDiagnosticForLogicalAndInLogicalOr(S
, OpLoc
, Bop
);
15055 } else if (Bop
->getOpcode() == BO_LOr
) {
15056 if (BinaryOperator
*RBop
= dyn_cast
<BinaryOperator
>(Bop
->getRHS())) {
15057 // If it's "a || b && string_literal || c" we didn't warn earlier for
15058 // "a || b && string_literal", but warn now.
15059 if (RBop
->getOpcode() == BO_LAnd
&&
15060 isa
<StringLiteral
>(RBop
->getRHS()->IgnoreParenImpCasts()))
15061 return EmitDiagnosticForLogicalAndInLogicalOr(S
, OpLoc
, RBop
);
15067 /// Look for '&&' in the right hand of a '||' expr.
15068 static void DiagnoseLogicalAndInLogicalOrRHS(Sema
&S
, SourceLocation OpLoc
,
15069 Expr
*LHSExpr
, Expr
*RHSExpr
) {
15070 if (BinaryOperator
*Bop
= dyn_cast
<BinaryOperator
>(RHSExpr
)) {
15071 if (Bop
->getOpcode() == BO_LAnd
) {
15072 // If it's "a || b && string_literal" don't warn since the precedence
15074 if (!isa
<StringLiteral
>(Bop
->getRHS()->IgnoreParenImpCasts()))
15075 return EmitDiagnosticForLogicalAndInLogicalOr(S
, OpLoc
, Bop
);
15080 /// Look for bitwise op in the left or right hand of a bitwise op with
15081 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
15082 /// the '&' expression in parentheses.
15083 static void DiagnoseBitwiseOpInBitwiseOp(Sema
&S
, BinaryOperatorKind Opc
,
15084 SourceLocation OpLoc
, Expr
*SubExpr
) {
15085 if (BinaryOperator
*Bop
= dyn_cast
<BinaryOperator
>(SubExpr
)) {
15086 if (Bop
->isBitwiseOp() && Bop
->getOpcode() < Opc
) {
15087 S
.Diag(Bop
->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op
)
15088 << Bop
->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc
)
15089 << Bop
->getSourceRange() << OpLoc
;
15090 SuggestParentheses(S
, Bop
->getOperatorLoc(),
15091 S
.PDiag(diag::note_precedence_silence
)
15092 << Bop
->getOpcodeStr(),
15093 Bop
->getSourceRange());
15098 static void DiagnoseAdditionInShift(Sema
&S
, SourceLocation OpLoc
,
15099 Expr
*SubExpr
, StringRef Shift
) {
15100 if (BinaryOperator
*Bop
= dyn_cast
<BinaryOperator
>(SubExpr
)) {
15101 if (Bop
->getOpcode() == BO_Add
|| Bop
->getOpcode() == BO_Sub
) {
15102 StringRef Op
= Bop
->getOpcodeStr();
15103 S
.Diag(Bop
->getOperatorLoc(), diag::warn_addition_in_bitshift
)
15104 << Bop
->getSourceRange() << OpLoc
<< Shift
<< Op
;
15105 SuggestParentheses(S
, Bop
->getOperatorLoc(),
15106 S
.PDiag(diag::note_precedence_silence
) << Op
,
15107 Bop
->getSourceRange());
15112 static void DiagnoseShiftCompare(Sema
&S
, SourceLocation OpLoc
,
15113 Expr
*LHSExpr
, Expr
*RHSExpr
) {
15114 CXXOperatorCallExpr
*OCE
= dyn_cast
<CXXOperatorCallExpr
>(LHSExpr
);
15118 FunctionDecl
*FD
= OCE
->getDirectCallee();
15119 if (!FD
|| !FD
->isOverloadedOperator())
15122 OverloadedOperatorKind Kind
= FD
->getOverloadedOperator();
15123 if (Kind
!= OO_LessLess
&& Kind
!= OO_GreaterGreater
)
15126 S
.Diag(OpLoc
, diag::warn_overloaded_shift_in_comparison
)
15127 << LHSExpr
->getSourceRange() << RHSExpr
->getSourceRange()
15128 << (Kind
== OO_LessLess
);
15129 SuggestParentheses(S
, OCE
->getOperatorLoc(),
15130 S
.PDiag(diag::note_precedence_silence
)
15131 << (Kind
== OO_LessLess
? "<<" : ">>"),
15132 OCE
->getSourceRange());
15133 SuggestParentheses(
15134 S
, OpLoc
, S
.PDiag(diag::note_evaluate_comparison_first
),
15135 SourceRange(OCE
->getArg(1)->getBeginLoc(), RHSExpr
->getEndLoc()));
15138 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15140 static void DiagnoseBinOpPrecedence(Sema
&Self
, BinaryOperatorKind Opc
,
15141 SourceLocation OpLoc
, Expr
*LHSExpr
,
15143 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15144 if (BinaryOperator::isBitwiseOp(Opc
))
15145 DiagnoseBitwisePrecedence(Self
, Opc
, OpLoc
, LHSExpr
, RHSExpr
);
15147 // Diagnose "arg1 & arg2 | arg3"
15148 if ((Opc
== BO_Or
|| Opc
== BO_Xor
) &&
15149 !OpLoc
.isMacroID()/* Don't warn in macros. */) {
15150 DiagnoseBitwiseOpInBitwiseOp(Self
, Opc
, OpLoc
, LHSExpr
);
15151 DiagnoseBitwiseOpInBitwiseOp(Self
, Opc
, OpLoc
, RHSExpr
);
15154 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15155 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15156 if (Opc
== BO_LOr
&& !OpLoc
.isMacroID()/* Don't warn in macros. */) {
15157 DiagnoseLogicalAndInLogicalOrLHS(Self
, OpLoc
, LHSExpr
, RHSExpr
);
15158 DiagnoseLogicalAndInLogicalOrRHS(Self
, OpLoc
, LHSExpr
, RHSExpr
);
15161 if ((Opc
== BO_Shl
&& LHSExpr
->getType()->isIntegralType(Self
.getASTContext()))
15162 || Opc
== BO_Shr
) {
15163 StringRef Shift
= BinaryOperator::getOpcodeStr(Opc
);
15164 DiagnoseAdditionInShift(Self
, OpLoc
, LHSExpr
, Shift
);
15165 DiagnoseAdditionInShift(Self
, OpLoc
, RHSExpr
, Shift
);
15168 // Warn on overloaded shift operators and comparisons, such as:
15170 if (BinaryOperator::isComparisonOp(Opc
))
15171 DiagnoseShiftCompare(Self
, OpLoc
, LHSExpr
, RHSExpr
);
15174 static void DetectPrecisionLossInComplexDivision(Sema
&S
, SourceLocation OpLoc
,
15176 if (auto *CT
= Operand
->getType()->getAs
<ComplexType
>()) {
15177 QualType ElementType
= CT
->getElementType();
15178 bool IsComplexRangePromoted
= S
.getLangOpts().getComplexRange() ==
15179 LangOptions::ComplexRangeKind::CX_Promoted
;
15180 if (ElementType
->isFloatingType() && IsComplexRangePromoted
) {
15181 ASTContext
&Ctx
= S
.getASTContext();
15182 QualType HigherElementType
= Ctx
.GetHigherPrecisionFPType(ElementType
);
15183 const llvm::fltSemantics
&ElementTypeSemantics
=
15184 Ctx
.getFloatTypeSemantics(ElementType
);
15185 const llvm::fltSemantics
&HigherElementTypeSemantics
=
15186 Ctx
.getFloatTypeSemantics(HigherElementType
);
15187 if (llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics
) * 2 + 1 >
15188 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics
)) {
15189 // Retain the location of the first use of higher precision type.
15190 if (!S
.LocationOfExcessPrecisionNotSatisfied
.isValid())
15191 S
.LocationOfExcessPrecisionNotSatisfied
= OpLoc
;
15192 for (auto &[Type
, Num
] : S
.ExcessPrecisionNotSatisfied
) {
15193 if (Type
== HigherElementType
) {
15198 S
.ExcessPrecisionNotSatisfied
.push_back(std::make_pair(
15199 HigherElementType
, S
.ExcessPrecisionNotSatisfied
.size()));
15205 ExprResult
Sema::ActOnBinOp(Scope
*S
, SourceLocation TokLoc
,
15206 tok::TokenKind Kind
,
15207 Expr
*LHSExpr
, Expr
*RHSExpr
) {
15208 BinaryOperatorKind Opc
= ConvertTokenKindToBinaryOpcode(Kind
);
15209 assert(LHSExpr
&& "ActOnBinOp(): missing left expression");
15210 assert(RHSExpr
&& "ActOnBinOp(): missing right expression");
15212 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15213 DiagnoseBinOpPrecedence(*this, Opc
, TokLoc
, LHSExpr
, RHSExpr
);
15215 // Emit warnings if the requested higher precision type equal to the current
15217 if (Kind
== tok::TokenKind::slash
)
15218 DetectPrecisionLossInComplexDivision(*this, TokLoc
, LHSExpr
);
15220 BuiltinCountedByRefKind K
=
15221 BinaryOperator::isAssignmentOp(Opc
) ? AssignmentKind
: BinaryExprKind
;
15223 CheckInvalidBuiltinCountedByRef(LHSExpr
, K
);
15224 CheckInvalidBuiltinCountedByRef(RHSExpr
, K
);
15226 return BuildBinOp(S
, TokLoc
, Opc
, LHSExpr
, RHSExpr
);
15229 void Sema::LookupBinOp(Scope
*S
, SourceLocation OpLoc
, BinaryOperatorKind Opc
,
15230 UnresolvedSetImpl
&Functions
) {
15231 OverloadedOperatorKind OverOp
= BinaryOperator::getOverloadedOperator(Opc
);
15232 if (OverOp
!= OO_None
&& OverOp
!= OO_Equal
)
15233 LookupOverloadedOperatorName(OverOp
, S
, Functions
);
15235 // In C++20 onwards, we may have a second operator to look up.
15236 if (getLangOpts().CPlusPlus20
) {
15237 if (OverloadedOperatorKind ExtraOp
= getRewrittenOverloadedOperator(OverOp
))
15238 LookupOverloadedOperatorName(ExtraOp
, S
, Functions
);
15242 /// Build an overloaded binary operator expression in the given scope.
15243 static ExprResult
BuildOverloadedBinOp(Sema
&S
, Scope
*Sc
, SourceLocation OpLoc
,
15244 BinaryOperatorKind Opc
,
15245 Expr
*LHS
, Expr
*RHS
) {
15248 // In the non-overloaded case, we warn about self-assignment (x = x) for
15249 // both simple assignment and certain compound assignments where algebra
15250 // tells us the operation yields a constant result. When the operator is
15251 // overloaded, we can't do the latter because we don't want to assume that
15252 // those algebraic identities still apply; for example, a path-building
15253 // library might use operator/= to append paths. But it's still reasonable
15254 // to assume that simple assignment is just moving/copying values around
15255 // and so self-assignment is likely a bug.
15256 DiagnoseSelfAssignment(S
, LHS
, RHS
, OpLoc
, false);
15264 CheckIdentityFieldAssignment(LHS
, RHS
, OpLoc
, S
);
15270 // Find all of the overloaded operators visible from this point.
15271 UnresolvedSet
<16> Functions
;
15272 S
.LookupBinOp(Sc
, OpLoc
, Opc
, Functions
);
15274 // Build the (potentially-overloaded, potentially-dependent)
15275 // binary operation.
15276 return S
.CreateOverloadedBinOp(OpLoc
, Opc
, Functions
, LHS
, RHS
);
15279 ExprResult
Sema::BuildBinOp(Scope
*S
, SourceLocation OpLoc
,
15280 BinaryOperatorKind Opc
,
15281 Expr
*LHSExpr
, Expr
*RHSExpr
) {
15282 ExprResult LHS
, RHS
;
15283 std::tie(LHS
, RHS
) = CorrectDelayedTyposInBinOp(*this, Opc
, LHSExpr
, RHSExpr
);
15284 if (!LHS
.isUsable() || !RHS
.isUsable())
15285 return ExprError();
15286 LHSExpr
= LHS
.get();
15287 RHSExpr
= RHS
.get();
15289 // We want to end up calling one of SemaPseudoObject::checkAssignment
15290 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15291 // both expressions are overloadable or either is type-dependent),
15292 // or CreateBuiltinBinOp (in any other case). We also want to get
15293 // any placeholder types out of the way.
15295 // Handle pseudo-objects in the LHS.
15296 if (const BuiltinType
*pty
= LHSExpr
->getType()->getAsPlaceholderType()) {
15297 // Assignments with a pseudo-object l-value need special analysis.
15298 if (pty
->getKind() == BuiltinType::PseudoObject
&&
15299 BinaryOperator::isAssignmentOp(Opc
))
15300 return PseudoObject().checkAssignment(S
, OpLoc
, Opc
, LHSExpr
, RHSExpr
);
15302 // Don't resolve overloads if the other type is overloadable.
15303 if (getLangOpts().CPlusPlus
&& pty
->getKind() == BuiltinType::Overload
) {
15304 // We can't actually test that if we still have a placeholder,
15305 // though. Fortunately, none of the exceptions we see in that
15306 // code below are valid when the LHS is an overload set. Note
15307 // that an overload set can be dependently-typed, but it never
15308 // instantiates to having an overloadable type.
15309 ExprResult resolvedRHS
= CheckPlaceholderExpr(RHSExpr
);
15310 if (resolvedRHS
.isInvalid()) return ExprError();
15311 RHSExpr
= resolvedRHS
.get();
15313 if (RHSExpr
->isTypeDependent() ||
15314 RHSExpr
->getType()->isOverloadableType())
15315 return BuildOverloadedBinOp(*this, S
, OpLoc
, Opc
, LHSExpr
, RHSExpr
);
15318 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15319 // template, diagnose the missing 'template' keyword instead of diagnosing
15320 // an invalid use of a bound member function.
15322 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15323 // to C++1z [over.over]/1.4, but we already checked for that case above.
15324 if (Opc
== BO_LT
&& inTemplateInstantiation() &&
15325 (pty
->getKind() == BuiltinType::BoundMember
||
15326 pty
->getKind() == BuiltinType::Overload
)) {
15327 auto *OE
= dyn_cast
<OverloadExpr
>(LHSExpr
);
15328 if (OE
&& !OE
->hasTemplateKeyword() && !OE
->hasExplicitTemplateArgs() &&
15329 llvm::any_of(OE
->decls(), [](NamedDecl
*ND
) {
15330 return isa
<FunctionTemplateDecl
>(ND
);
15332 Diag(OE
->getQualifier() ? OE
->getQualifierLoc().getBeginLoc()
15333 : OE
->getNameLoc(),
15334 diag::err_template_kw_missing
)
15335 << OE
->getName().getAsString() << "";
15336 return ExprError();
15340 ExprResult LHS
= CheckPlaceholderExpr(LHSExpr
);
15341 if (LHS
.isInvalid()) return ExprError();
15342 LHSExpr
= LHS
.get();
15345 // Handle pseudo-objects in the RHS.
15346 if (const BuiltinType
*pty
= RHSExpr
->getType()->getAsPlaceholderType()) {
15347 // An overload in the RHS can potentially be resolved by the type
15348 // being assigned to.
15349 if (Opc
== BO_Assign
&& pty
->getKind() == BuiltinType::Overload
) {
15350 if (getLangOpts().CPlusPlus
&&
15351 (LHSExpr
->isTypeDependent() || RHSExpr
->isTypeDependent() ||
15352 LHSExpr
->getType()->isOverloadableType()))
15353 return BuildOverloadedBinOp(*this, S
, OpLoc
, Opc
, LHSExpr
, RHSExpr
);
15355 return CreateBuiltinBinOp(OpLoc
, Opc
, LHSExpr
, RHSExpr
);
15358 // Don't resolve overloads if the other type is overloadable.
15359 if (getLangOpts().CPlusPlus
&& pty
->getKind() == BuiltinType::Overload
&&
15360 LHSExpr
->getType()->isOverloadableType())
15361 return BuildOverloadedBinOp(*this, S
, OpLoc
, Opc
, LHSExpr
, RHSExpr
);
15363 ExprResult resolvedRHS
= CheckPlaceholderExpr(RHSExpr
);
15364 if (!resolvedRHS
.isUsable()) return ExprError();
15365 RHSExpr
= resolvedRHS
.get();
15368 if (getLangOpts().CPlusPlus
) {
15369 // Otherwise, build an overloaded op if either expression is type-dependent
15370 // or has an overloadable type.
15371 if (LHSExpr
->isTypeDependent() || RHSExpr
->isTypeDependent() ||
15372 LHSExpr
->getType()->isOverloadableType() ||
15373 RHSExpr
->getType()->isOverloadableType())
15374 return BuildOverloadedBinOp(*this, S
, OpLoc
, Opc
, LHSExpr
, RHSExpr
);
15377 if (getLangOpts().RecoveryAST
&&
15378 (LHSExpr
->isTypeDependent() || RHSExpr
->isTypeDependent())) {
15379 assert(!getLangOpts().CPlusPlus
);
15380 assert((LHSExpr
->containsErrors() || RHSExpr
->containsErrors()) &&
15381 "Should only occur in error-recovery path.");
15382 if (BinaryOperator::isCompoundAssignmentOp(Opc
))
15384 // An assignment expression has the value of the left operand after the
15385 // assignment, but is not an lvalue.
15386 return CompoundAssignOperator::Create(
15387 Context
, LHSExpr
, RHSExpr
, Opc
,
15388 LHSExpr
->getType().getUnqualifiedType(), VK_PRValue
, OK_Ordinary
,
15389 OpLoc
, CurFPFeatureOverrides());
15390 QualType ResultType
;
15393 ResultType
= LHSExpr
->getType().getUnqualifiedType();
15403 // These operators have a fixed result type regardless of operands.
15404 ResultType
= Context
.IntTy
;
15407 ResultType
= RHSExpr
->getType();
15410 ResultType
= Context
.DependentTy
;
15413 return BinaryOperator::Create(Context
, LHSExpr
, RHSExpr
, Opc
, ResultType
,
15414 VK_PRValue
, OK_Ordinary
, OpLoc
,
15415 CurFPFeatureOverrides());
15418 // Build a built-in binary operation.
15419 return CreateBuiltinBinOp(OpLoc
, Opc
, LHSExpr
, RHSExpr
);
15422 static bool isOverflowingIntegerType(ASTContext
&Ctx
, QualType T
) {
15423 if (T
.isNull() || T
->isDependentType())
15426 if (!Ctx
.isPromotableIntegerType(T
))
15429 return Ctx
.getIntWidth(T
) >= Ctx
.getIntWidth(Ctx
.IntTy
);
15432 ExprResult
Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc
,
15433 UnaryOperatorKind Opc
, Expr
*InputExpr
,
15435 ExprResult Input
= InputExpr
;
15436 ExprValueKind VK
= VK_PRValue
;
15437 ExprObjectKind OK
= OK_Ordinary
;
15438 QualType resultType
;
15439 bool CanOverflow
= false;
15441 bool ConvertHalfVec
= false;
15442 if (getLangOpts().OpenCL
) {
15443 QualType Ty
= InputExpr
->getType();
15444 // The only legal unary operation for atomics is '&'.
15445 if ((Opc
!= UO_AddrOf
&& Ty
->isAtomicType()) ||
15446 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15447 // only with a builtin functions and therefore should be disallowed here.
15448 (Ty
->isImageType() || Ty
->isSamplerT() || Ty
->isPipeType()
15449 || Ty
->isBlockPointerType())) {
15450 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
15451 << InputExpr
->getType()
15452 << Input
.get()->getSourceRange());
15456 if (getLangOpts().HLSL
&& OpLoc
.isValid()) {
15457 if (Opc
== UO_AddrOf
)
15458 return ExprError(Diag(OpLoc
, diag::err_hlsl_operator_unsupported
) << 0);
15459 if (Opc
== UO_Deref
)
15460 return ExprError(Diag(OpLoc
, diag::err_hlsl_operator_unsupported
) << 1);
15463 if (InputExpr
->isTypeDependent() &&
15464 InputExpr
->getType()->isSpecificBuiltinType(BuiltinType::Dependent
)) {
15465 resultType
= Context
.DependentTy
;
15473 CheckIncrementDecrementOperand(*this, Input
.get(), VK
, OK
, OpLoc
,
15474 Opc
== UO_PreInc
|| Opc
== UO_PostInc
,
15475 Opc
== UO_PreInc
|| Opc
== UO_PreDec
);
15476 CanOverflow
= isOverflowingIntegerType(Context
, resultType
);
15479 resultType
= CheckAddressOfOperand(Input
, OpLoc
);
15480 CheckAddressOfNoDeref(InputExpr
);
15481 RecordModifiableNonNullParam(*this, InputExpr
);
15484 Input
= DefaultFunctionArrayLvalueConversion(Input
.get());
15485 if (Input
.isInvalid())
15486 return ExprError();
15488 CheckIndirectionOperand(*this, Input
.get(), VK
, OpLoc
, IsAfterAmp
);
15493 CanOverflow
= Opc
== UO_Minus
&&
15494 isOverflowingIntegerType(Context
, Input
.get()->getType());
15495 Input
= UsualUnaryConversions(Input
.get());
15496 if (Input
.isInvalid())
15497 return ExprError();
15498 // Unary plus and minus require promoting an operand of half vector to a
15499 // float vector and truncating the result back to a half vector. For now,
15500 // we do this only when HalfArgsAndReturns is set (that is, when the
15501 // target is arm or arm64).
15502 ConvertHalfVec
= needsConversionOfHalfVec(true, Context
, Input
.get());
15504 // If the operand is a half vector, promote it to a float vector.
15505 if (ConvertHalfVec
)
15506 Input
= convertVector(Input
.get(), Context
.FloatTy
, *this);
15507 resultType
= Input
.get()->getType();
15508 if (resultType
->isArithmeticType()) // C99 6.5.3.3p1
15510 else if (resultType
->isVectorType() &&
15511 // The z vector extensions don't allow + or - with bool vectors.
15512 (!Context
.getLangOpts().ZVector
||
15513 resultType
->castAs
<VectorType
>()->getVectorKind() !=
15514 VectorKind::AltiVecBool
))
15516 else if (resultType
->isSveVLSBuiltinType()) // SVE vectors allow + and -
15518 else if (getLangOpts().CPlusPlus
&& // C++ [expr.unary.op]p6
15519 Opc
== UO_Plus
&& resultType
->isPointerType())
15522 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
15523 << resultType
<< Input
.get()->getSourceRange());
15525 case UO_Not
: // bitwise complement
15526 Input
= UsualUnaryConversions(Input
.get());
15527 if (Input
.isInvalid())
15528 return ExprError();
15529 resultType
= Input
.get()->getType();
15530 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15531 if (resultType
->isComplexType() || resultType
->isComplexIntegerType())
15532 // C99 does not support '~' for complex conjugation.
15533 Diag(OpLoc
, diag::ext_integer_complement_complex
)
15534 << resultType
<< Input
.get()->getSourceRange();
15535 else if (resultType
->hasIntegerRepresentation())
15537 else if (resultType
->isExtVectorType() && Context
.getLangOpts().OpenCL
) {
15538 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15539 // on vector float types.
15540 QualType T
= resultType
->castAs
<ExtVectorType
>()->getElementType();
15541 if (!T
->isIntegerType())
15542 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
15543 << resultType
<< Input
.get()->getSourceRange());
15545 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
15546 << resultType
<< Input
.get()->getSourceRange());
15550 case UO_LNot
: // logical negation
15551 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15552 Input
= DefaultFunctionArrayLvalueConversion(Input
.get());
15553 if (Input
.isInvalid())
15554 return ExprError();
15555 resultType
= Input
.get()->getType();
15557 // Though we still have to promote half FP to float...
15558 if (resultType
->isHalfType() && !Context
.getLangOpts().NativeHalfType
) {
15559 Input
= ImpCastExprToType(Input
.get(), Context
.FloatTy
, CK_FloatingCast
)
15561 resultType
= Context
.FloatTy
;
15564 // WebAsembly tables can't be used in unary expressions.
15565 if (resultType
->isPointerType() &&
15566 resultType
->getPointeeType().isWebAssemblyReferenceType()) {
15567 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
15568 << resultType
<< Input
.get()->getSourceRange());
15571 if (resultType
->isScalarType() && !isScopedEnumerationType(resultType
)) {
15572 // C99 6.5.3.3p1: ok, fallthrough;
15573 if (Context
.getLangOpts().CPlusPlus
) {
15574 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15575 // operand contextually converted to bool.
15576 Input
= ImpCastExprToType(Input
.get(), Context
.BoolTy
,
15577 ScalarTypeToBooleanCastKind(resultType
));
15578 } else if (Context
.getLangOpts().OpenCL
&&
15579 Context
.getLangOpts().OpenCLVersion
< 120) {
15580 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15581 // operate on scalar float types.
15582 if (!resultType
->isIntegerType() && !resultType
->isPointerType())
15583 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
15584 << resultType
<< Input
.get()->getSourceRange());
15586 } else if (resultType
->isExtVectorType()) {
15587 if (Context
.getLangOpts().OpenCL
&&
15588 Context
.getLangOpts().getOpenCLCompatibleVersion() < 120) {
15589 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15590 // operate on vector float types.
15591 QualType T
= resultType
->castAs
<ExtVectorType
>()->getElementType();
15592 if (!T
->isIntegerType())
15593 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
15594 << resultType
<< Input
.get()->getSourceRange());
15596 // Vector logical not returns the signed variant of the operand type.
15597 resultType
= GetSignedVectorType(resultType
);
15599 } else if (Context
.getLangOpts().CPlusPlus
&&
15600 resultType
->isVectorType()) {
15601 const VectorType
*VTy
= resultType
->castAs
<VectorType
>();
15602 if (VTy
->getVectorKind() != VectorKind::Generic
)
15603 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
15604 << resultType
<< Input
.get()->getSourceRange());
15606 // Vector logical not returns the signed variant of the operand type.
15607 resultType
= GetSignedVectorType(resultType
);
15610 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
15611 << resultType
<< Input
.get()->getSourceRange());
15614 // LNot always has type int. C99 6.5.3.3p5.
15615 // In C++, it's bool. C++ 5.3.1p8
15616 resultType
= Context
.getLogicalOperationType();
15620 resultType
= CheckRealImagOperand(*this, Input
, OpLoc
, Opc
== UO_Real
);
15621 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
15622 // ordinary complex l-values to ordinary l-values and all other values to
15624 if (Input
.isInvalid())
15625 return ExprError();
15626 if (Opc
== UO_Real
|| Input
.get()->getType()->isAnyComplexType()) {
15627 if (Input
.get()->isGLValue() &&
15628 Input
.get()->getObjectKind() == OK_Ordinary
)
15629 VK
= Input
.get()->getValueKind();
15630 } else if (!getLangOpts().CPlusPlus
) {
15631 // In C, a volatile scalar is read by __imag. In C++, it is not.
15632 Input
= DefaultLvalueConversion(Input
.get());
15636 resultType
= Input
.get()->getType();
15637 VK
= Input
.get()->getValueKind();
15638 OK
= Input
.get()->getObjectKind();
15641 // It's unnecessary to represent the pass-through operator co_await in the
15642 // AST; just return the input expression instead.
15643 assert(!Input
.get()->getType()->isDependentType() &&
15644 "the co_await expression must be non-dependant before "
15645 "building operator co_await");
15649 if (resultType
.isNull() || Input
.isInvalid())
15650 return ExprError();
15652 // Check for array bounds violations in the operand of the UnaryOperator,
15653 // except for the '*' and '&' operators that have to be handled specially
15654 // by CheckArrayAccess (as there are special cases like &array[arraysize]
15655 // that are explicitly defined as valid by the standard).
15656 if (Opc
!= UO_AddrOf
&& Opc
!= UO_Deref
)
15657 CheckArrayAccess(Input
.get());
15660 UnaryOperator::Create(Context
, Input
.get(), Opc
, resultType
, VK
, OK
,
15661 OpLoc
, CanOverflow
, CurFPFeatureOverrides());
15663 if (Opc
== UO_Deref
&& UO
->getType()->hasAttr(attr::NoDeref
) &&
15664 !isa
<ArrayType
>(UO
->getType().getDesugaredType(Context
)) &&
15665 !isUnevaluatedContext())
15666 ExprEvalContexts
.back().PossibleDerefs
.insert(UO
);
15668 // Convert the result back to a half vector.
15669 if (ConvertHalfVec
)
15670 return convertVector(UO
, Context
.HalfTy
, *this);
15674 bool Sema::isQualifiedMemberAccess(Expr
*E
) {
15675 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(E
)) {
15676 if (!DRE
->getQualifier())
15679 ValueDecl
*VD
= DRE
->getDecl();
15680 if (!VD
->isCXXClassMember())
15683 if (isa
<FieldDecl
>(VD
) || isa
<IndirectFieldDecl
>(VD
))
15685 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(VD
))
15686 return Method
->isImplicitObjectMemberFunction();
15691 if (UnresolvedLookupExpr
*ULE
= dyn_cast
<UnresolvedLookupExpr
>(E
)) {
15692 if (!ULE
->getQualifier())
15695 for (NamedDecl
*D
: ULE
->decls()) {
15696 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(D
)) {
15697 if (Method
->isImplicitObjectMemberFunction())
15700 // Overload set does not contain methods.
15711 ExprResult
Sema::BuildUnaryOp(Scope
*S
, SourceLocation OpLoc
,
15712 UnaryOperatorKind Opc
, Expr
*Input
,
15714 // First things first: handle placeholders so that the
15715 // overloaded-operator check considers the right type.
15716 if (const BuiltinType
*pty
= Input
->getType()->getAsPlaceholderType()) {
15717 // Increment and decrement of pseudo-object references.
15718 if (pty
->getKind() == BuiltinType::PseudoObject
&&
15719 UnaryOperator::isIncrementDecrementOp(Opc
))
15720 return PseudoObject().checkIncDec(S
, OpLoc
, Opc
, Input
);
15722 // extension is always a builtin operator.
15723 if (Opc
== UO_Extension
)
15724 return CreateBuiltinUnaryOp(OpLoc
, Opc
, Input
);
15726 // & gets special logic for several kinds of placeholder.
15727 // The builtin code knows what to do.
15728 if (Opc
== UO_AddrOf
&&
15729 (pty
->getKind() == BuiltinType::Overload
||
15730 pty
->getKind() == BuiltinType::UnknownAny
||
15731 pty
->getKind() == BuiltinType::BoundMember
))
15732 return CreateBuiltinUnaryOp(OpLoc
, Opc
, Input
);
15734 // Anything else needs to be handled now.
15735 ExprResult Result
= CheckPlaceholderExpr(Input
);
15736 if (Result
.isInvalid()) return ExprError();
15737 Input
= Result
.get();
15740 if (getLangOpts().CPlusPlus
&& Input
->getType()->isOverloadableType() &&
15741 UnaryOperator::getOverloadedOperator(Opc
) != OO_None
&&
15742 !(Opc
== UO_AddrOf
&& isQualifiedMemberAccess(Input
))) {
15743 // Find all of the overloaded operators visible from this point.
15744 UnresolvedSet
<16> Functions
;
15745 OverloadedOperatorKind OverOp
= UnaryOperator::getOverloadedOperator(Opc
);
15746 if (S
&& OverOp
!= OO_None
)
15747 LookupOverloadedOperatorName(OverOp
, S
, Functions
);
15749 return CreateOverloadedUnaryOp(OpLoc
, Opc
, Functions
, Input
);
15752 return CreateBuiltinUnaryOp(OpLoc
, Opc
, Input
, IsAfterAmp
);
15755 ExprResult
Sema::ActOnUnaryOp(Scope
*S
, SourceLocation OpLoc
, tok::TokenKind Op
,
15756 Expr
*Input
, bool IsAfterAmp
) {
15757 return BuildUnaryOp(S
, OpLoc
, ConvertTokenKindToUnaryOpcode(Op
), Input
,
15761 ExprResult
Sema::ActOnAddrLabel(SourceLocation OpLoc
, SourceLocation LabLoc
,
15762 LabelDecl
*TheDecl
) {
15763 TheDecl
->markUsed(Context
);
15764 // Create the AST node. The address of a label always has type 'void*'.
15765 auto *Res
= new (Context
) AddrLabelExpr(
15766 OpLoc
, LabLoc
, TheDecl
, Context
.getPointerType(Context
.VoidTy
));
15768 if (getCurFunction())
15769 getCurFunction()->AddrLabels
.push_back(Res
);
15774 void Sema::ActOnStartStmtExpr() {
15775 PushExpressionEvaluationContext(ExprEvalContexts
.back().Context
);
15776 // Make sure we diagnose jumping into a statement expression.
15777 setFunctionHasBranchProtectedScope();
15780 void Sema::ActOnStmtExprError() {
15781 // Note that function is also called by TreeTransform when leaving a
15782 // StmtExpr scope without rebuilding anything.
15784 DiscardCleanupsInEvaluationContext();
15785 PopExpressionEvaluationContext();
15788 ExprResult
Sema::ActOnStmtExpr(Scope
*S
, SourceLocation LPLoc
, Stmt
*SubStmt
,
15789 SourceLocation RPLoc
) {
15790 return BuildStmtExpr(LPLoc
, SubStmt
, RPLoc
, getTemplateDepth(S
));
15793 ExprResult
Sema::BuildStmtExpr(SourceLocation LPLoc
, Stmt
*SubStmt
,
15794 SourceLocation RPLoc
, unsigned TemplateDepth
) {
15795 assert(SubStmt
&& isa
<CompoundStmt
>(SubStmt
) && "Invalid action invocation!");
15796 CompoundStmt
*Compound
= cast
<CompoundStmt
>(SubStmt
);
15798 if (hasAnyUnrecoverableErrorsInThisFunction())
15799 DiscardCleanupsInEvaluationContext();
15800 assert(!Cleanup
.exprNeedsCleanups() &&
15801 "cleanups within StmtExpr not correctly bound!");
15802 PopExpressionEvaluationContext();
15804 // FIXME: there are a variety of strange constraints to enforce here, for
15805 // example, it is not possible to goto into a stmt expression apparently.
15806 // More semantic analysis is needed.
15808 // If there are sub-stmts in the compound stmt, take the type of the last one
15809 // as the type of the stmtexpr.
15810 QualType Ty
= Context
.VoidTy
;
15811 bool StmtExprMayBindToTemp
= false;
15812 if (!Compound
->body_empty()) {
15813 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15814 if (const auto *LastStmt
=
15815 dyn_cast
<ValueStmt
>(Compound
->getStmtExprResult())) {
15816 if (const Expr
*Value
= LastStmt
->getExprStmt()) {
15817 StmtExprMayBindToTemp
= true;
15818 Ty
= Value
->getType();
15823 // FIXME: Check that expression type is complete/non-abstract; statement
15824 // expressions are not lvalues.
15825 Expr
*ResStmtExpr
=
15826 new (Context
) StmtExpr(Compound
, Ty
, LPLoc
, RPLoc
, TemplateDepth
);
15827 if (StmtExprMayBindToTemp
)
15828 return MaybeBindToTemporary(ResStmtExpr
);
15829 return ResStmtExpr
;
15832 ExprResult
Sema::ActOnStmtExprResult(ExprResult ER
) {
15833 if (ER
.isInvalid())
15834 return ExprError();
15836 // Do function/array conversion on the last expression, but not
15837 // lvalue-to-rvalue. However, initialize an unqualified type.
15838 ER
= DefaultFunctionArrayConversion(ER
.get());
15839 if (ER
.isInvalid())
15840 return ExprError();
15841 Expr
*E
= ER
.get();
15843 if (E
->isTypeDependent())
15846 // In ARC, if the final expression ends in a consume, splice
15847 // the consume out and bind it later. In the alternate case
15848 // (when dealing with a retainable type), the result
15849 // initialization will create a produce. In both cases the
15850 // result will be +1, and we'll need to balance that out with
15852 auto *Cast
= dyn_cast
<ImplicitCastExpr
>(E
);
15853 if (Cast
&& Cast
->getCastKind() == CK_ARCConsumeObject
)
15854 return Cast
->getSubExpr();
15856 // FIXME: Provide a better location for the initialization.
15857 return PerformCopyInitialization(
15858 InitializedEntity::InitializeStmtExprResult(
15859 E
->getBeginLoc(), E
->getType().getUnqualifiedType()),
15860 SourceLocation(), E
);
15863 ExprResult
Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc
,
15864 TypeSourceInfo
*TInfo
,
15865 ArrayRef
<OffsetOfComponent
> Components
,
15866 SourceLocation RParenLoc
) {
15867 QualType ArgTy
= TInfo
->getType();
15868 bool Dependent
= ArgTy
->isDependentType();
15869 SourceRange TypeRange
= TInfo
->getTypeLoc().getLocalSourceRange();
15871 // We must have at least one component that refers to the type, and the first
15872 // one is known to be a field designator. Verify that the ArgTy represents
15873 // a struct/union/class.
15874 if (!Dependent
&& !ArgTy
->isRecordType())
15875 return ExprError(Diag(BuiltinLoc
, diag::err_offsetof_record_type
)
15876 << ArgTy
<< TypeRange
);
15878 // Type must be complete per C99 7.17p3 because a declaring a variable
15879 // with an incomplete type would be ill-formed.
15881 && RequireCompleteType(BuiltinLoc
, ArgTy
,
15882 diag::err_offsetof_incomplete_type
, TypeRange
))
15883 return ExprError();
15885 bool DidWarnAboutNonPOD
= false;
15886 QualType CurrentType
= ArgTy
;
15887 SmallVector
<OffsetOfNode
, 4> Comps
;
15888 SmallVector
<Expr
*, 4> Exprs
;
15889 for (const OffsetOfComponent
&OC
: Components
) {
15890 if (OC
.isBrackets
) {
15891 // Offset of an array sub-field. TODO: Should we allow vector elements?
15892 if (!CurrentType
->isDependentType()) {
15893 const ArrayType
*AT
= Context
.getAsArrayType(CurrentType
);
15895 return ExprError(Diag(OC
.LocEnd
, diag::err_offsetof_array_type
)
15897 CurrentType
= AT
->getElementType();
15899 CurrentType
= Context
.DependentTy
;
15901 ExprResult IdxRval
= DefaultLvalueConversion(static_cast<Expr
*>(OC
.U
.E
));
15902 if (IdxRval
.isInvalid())
15903 return ExprError();
15904 Expr
*Idx
= IdxRval
.get();
15906 // The expression must be an integral expression.
15907 // FIXME: An integral constant expression?
15908 if (!Idx
->isTypeDependent() && !Idx
->isValueDependent() &&
15909 !Idx
->getType()->isIntegerType())
15911 Diag(Idx
->getBeginLoc(), diag::err_typecheck_subscript_not_integer
)
15912 << Idx
->getSourceRange());
15914 // Record this array index.
15915 Comps
.push_back(OffsetOfNode(OC
.LocStart
, Exprs
.size(), OC
.LocEnd
));
15916 Exprs
.push_back(Idx
);
15920 // Offset of a field.
15921 if (CurrentType
->isDependentType()) {
15922 // We have the offset of a field, but we can't look into the dependent
15923 // type. Just record the identifier of the field.
15924 Comps
.push_back(OffsetOfNode(OC
.LocStart
, OC
.U
.IdentInfo
, OC
.LocEnd
));
15925 CurrentType
= Context
.DependentTy
;
15929 // We need to have a complete type to look into.
15930 if (RequireCompleteType(OC
.LocStart
, CurrentType
,
15931 diag::err_offsetof_incomplete_type
))
15932 return ExprError();
15934 // Look for the designated field.
15935 const RecordType
*RC
= CurrentType
->getAs
<RecordType
>();
15937 return ExprError(Diag(OC
.LocEnd
, diag::err_offsetof_record_type
)
15939 RecordDecl
*RD
= RC
->getDecl();
15941 // C++ [lib.support.types]p5:
15942 // The macro offsetof accepts a restricted set of type arguments in this
15943 // International Standard. type shall be a POD structure or a POD union
15945 // C++11 [support.types]p4:
15946 // If type is not a standard-layout class (Clause 9), the results are
15948 if (CXXRecordDecl
*CRD
= dyn_cast
<CXXRecordDecl
>(RD
)) {
15949 bool IsSafe
= LangOpts
.CPlusPlus11
? CRD
->isStandardLayout() : CRD
->isPOD();
15951 LangOpts
.CPlusPlus11
? diag::ext_offsetof_non_standardlayout_type
15952 : diag::ext_offsetof_non_pod_type
;
15954 if (!IsSafe
&& !DidWarnAboutNonPOD
&& !isUnevaluatedContext()) {
15955 Diag(BuiltinLoc
, DiagID
)
15956 << SourceRange(Components
[0].LocStart
, OC
.LocEnd
) << CurrentType
;
15957 DidWarnAboutNonPOD
= true;
15961 // Look for the field.
15962 LookupResult
R(*this, OC
.U
.IdentInfo
, OC
.LocStart
, LookupMemberName
);
15963 LookupQualifiedName(R
, RD
);
15964 FieldDecl
*MemberDecl
= R
.getAsSingle
<FieldDecl
>();
15965 IndirectFieldDecl
*IndirectMemberDecl
= nullptr;
15967 if ((IndirectMemberDecl
= R
.getAsSingle
<IndirectFieldDecl
>()))
15968 MemberDecl
= IndirectMemberDecl
->getAnonField();
15972 // Lookup could be ambiguous when looking up a placeholder variable
15973 // __builtin_offsetof(S, _).
15974 // In that case we would already have emitted a diagnostic
15975 if (!R
.isAmbiguous())
15976 Diag(BuiltinLoc
, diag::err_no_member
)
15977 << OC
.U
.IdentInfo
<< RD
<< SourceRange(OC
.LocStart
, OC
.LocEnd
);
15978 return ExprError();
15982 // (If the specified member is a bit-field, the behavior is undefined.)
15984 // We diagnose this as an error.
15985 if (MemberDecl
->isBitField()) {
15986 Diag(OC
.LocEnd
, diag::err_offsetof_bitfield
)
15987 << MemberDecl
->getDeclName()
15988 << SourceRange(BuiltinLoc
, RParenLoc
);
15989 Diag(MemberDecl
->getLocation(), diag::note_bitfield_decl
);
15990 return ExprError();
15993 RecordDecl
*Parent
= MemberDecl
->getParent();
15994 if (IndirectMemberDecl
)
15995 Parent
= cast
<RecordDecl
>(IndirectMemberDecl
->getDeclContext());
15997 // If the member was found in a base class, introduce OffsetOfNodes for
15998 // the base class indirections.
15999 CXXBasePaths Paths
;
16000 if (IsDerivedFrom(OC
.LocStart
, CurrentType
, Context
.getTypeDeclType(Parent
),
16002 if (Paths
.getDetectedVirtual()) {
16003 Diag(OC
.LocEnd
, diag::err_offsetof_field_of_virtual_base
)
16004 << MemberDecl
->getDeclName()
16005 << SourceRange(BuiltinLoc
, RParenLoc
);
16006 return ExprError();
16009 CXXBasePath
&Path
= Paths
.front();
16010 for (const CXXBasePathElement
&B
: Path
)
16011 Comps
.push_back(OffsetOfNode(B
.Base
));
16014 if (IndirectMemberDecl
) {
16015 for (auto *FI
: IndirectMemberDecl
->chain()) {
16016 assert(isa
<FieldDecl
>(FI
));
16017 Comps
.push_back(OffsetOfNode(OC
.LocStart
,
16018 cast
<FieldDecl
>(FI
), OC
.LocEnd
));
16021 Comps
.push_back(OffsetOfNode(OC
.LocStart
, MemberDecl
, OC
.LocEnd
));
16023 CurrentType
= MemberDecl
->getType().getNonReferenceType();
16026 return OffsetOfExpr::Create(Context
, Context
.getSizeType(), BuiltinLoc
, TInfo
,
16027 Comps
, Exprs
, RParenLoc
);
16030 ExprResult
Sema::ActOnBuiltinOffsetOf(Scope
*S
,
16031 SourceLocation BuiltinLoc
,
16032 SourceLocation TypeLoc
,
16033 ParsedType ParsedArgTy
,
16034 ArrayRef
<OffsetOfComponent
> Components
,
16035 SourceLocation RParenLoc
) {
16037 TypeSourceInfo
*ArgTInfo
;
16038 QualType ArgTy
= GetTypeFromParser(ParsedArgTy
, &ArgTInfo
);
16039 if (ArgTy
.isNull())
16040 return ExprError();
16043 ArgTInfo
= Context
.getTrivialTypeSourceInfo(ArgTy
, TypeLoc
);
16045 return BuildBuiltinOffsetOf(BuiltinLoc
, ArgTInfo
, Components
, RParenLoc
);
16049 ExprResult
Sema::ActOnChooseExpr(SourceLocation BuiltinLoc
,
16051 Expr
*LHSExpr
, Expr
*RHSExpr
,
16052 SourceLocation RPLoc
) {
16053 assert((CondExpr
&& LHSExpr
&& RHSExpr
) && "Missing type argument(s)");
16055 ExprValueKind VK
= VK_PRValue
;
16056 ExprObjectKind OK
= OK_Ordinary
;
16058 bool CondIsTrue
= false;
16059 if (CondExpr
->isTypeDependent() || CondExpr
->isValueDependent()) {
16060 resType
= Context
.DependentTy
;
16062 // The conditional expression is required to be a constant expression.
16063 llvm::APSInt
condEval(32);
16064 ExprResult CondICE
= VerifyIntegerConstantExpression(
16065 CondExpr
, &condEval
, diag::err_typecheck_choose_expr_requires_constant
);
16066 if (CondICE
.isInvalid())
16067 return ExprError();
16068 CondExpr
= CondICE
.get();
16069 CondIsTrue
= condEval
.getZExtValue();
16071 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16072 Expr
*ActiveExpr
= CondIsTrue
? LHSExpr
: RHSExpr
;
16074 resType
= ActiveExpr
->getType();
16075 VK
= ActiveExpr
->getValueKind();
16076 OK
= ActiveExpr
->getObjectKind();
16079 return new (Context
) ChooseExpr(BuiltinLoc
, CondExpr
, LHSExpr
, RHSExpr
,
16080 resType
, VK
, OK
, RPLoc
, CondIsTrue
);
16083 //===----------------------------------------------------------------------===//
16084 // Clang Extensions.
16085 //===----------------------------------------------------------------------===//
16087 void Sema::ActOnBlockStart(SourceLocation CaretLoc
, Scope
*CurScope
) {
16088 BlockDecl
*Block
= BlockDecl::Create(Context
, CurContext
, CaretLoc
);
16090 if (LangOpts
.CPlusPlus
) {
16091 MangleNumberingContext
*MCtx
;
16092 Decl
*ManglingContextDecl
;
16093 std::tie(MCtx
, ManglingContextDecl
) =
16094 getCurrentMangleNumberContext(Block
->getDeclContext());
16096 unsigned ManglingNumber
= MCtx
->getManglingNumber(Block
);
16097 Block
->setBlockMangling(ManglingNumber
, ManglingContextDecl
);
16101 PushBlockScope(CurScope
, Block
);
16102 CurContext
->addDecl(Block
);
16104 PushDeclContext(CurScope
, Block
);
16106 CurContext
= Block
;
16108 getCurBlock()->HasImplicitReturnType
= true;
16110 // Enter a new evaluation context to insulate the block from any
16111 // cleanups from the enclosing full-expression.
16112 PushExpressionEvaluationContext(
16113 ExpressionEvaluationContext::PotentiallyEvaluated
);
16116 void Sema::ActOnBlockArguments(SourceLocation CaretLoc
, Declarator
&ParamInfo
,
16118 assert(ParamInfo
.getIdentifier() == nullptr &&
16119 "block-id should have no identifier!");
16120 assert(ParamInfo
.getContext() == DeclaratorContext::BlockLiteral
);
16121 BlockScopeInfo
*CurBlock
= getCurBlock();
16123 TypeSourceInfo
*Sig
= GetTypeForDeclarator(ParamInfo
);
16124 QualType T
= Sig
->getType();
16125 DiagnoseUnexpandedParameterPack(CaretLoc
, Sig
, UPPC_Block
);
16127 // GetTypeForDeclarator always produces a function type for a block
16128 // literal signature. Furthermore, it is always a FunctionProtoType
16129 // unless the function was written with a typedef.
16130 assert(T
->isFunctionType() &&
16131 "GetTypeForDeclarator made a non-function block signature");
16133 // Look for an explicit signature in that function type.
16134 FunctionProtoTypeLoc ExplicitSignature
;
16136 if ((ExplicitSignature
= Sig
->getTypeLoc()
16137 .getAsAdjusted
<FunctionProtoTypeLoc
>())) {
16139 // Check whether that explicit signature was synthesized by
16140 // GetTypeForDeclarator. If so, don't save that as part of the
16141 // written signature.
16142 if (ExplicitSignature
.getLocalRangeBegin() ==
16143 ExplicitSignature
.getLocalRangeEnd()) {
16144 // This would be much cheaper if we stored TypeLocs instead of
16145 // TypeSourceInfos.
16146 TypeLoc Result
= ExplicitSignature
.getReturnLoc();
16147 unsigned Size
= Result
.getFullDataSize();
16148 Sig
= Context
.CreateTypeSourceInfo(Result
.getType(), Size
);
16149 Sig
->getTypeLoc().initializeFullCopy(Result
, Size
);
16151 ExplicitSignature
= FunctionProtoTypeLoc();
16155 CurBlock
->TheDecl
->setSignatureAsWritten(Sig
);
16156 CurBlock
->FunctionType
= T
;
16158 const auto *Fn
= T
->castAs
<FunctionType
>();
16159 QualType RetTy
= Fn
->getReturnType();
16161 (isa
<FunctionProtoType
>(Fn
) && cast
<FunctionProtoType
>(Fn
)->isVariadic());
16163 CurBlock
->TheDecl
->setIsVariadic(isVariadic
);
16165 // Context.DependentTy is used as a placeholder for a missing block
16166 // return type. TODO: what should we do with declarators like:
16168 // If the answer is "apply template argument deduction"....
16169 if (RetTy
!= Context
.DependentTy
) {
16170 CurBlock
->ReturnType
= RetTy
;
16171 CurBlock
->TheDecl
->setBlockMissingReturnType(false);
16172 CurBlock
->HasImplicitReturnType
= false;
16175 // Push block parameters from the declarator if we had them.
16176 SmallVector
<ParmVarDecl
*, 8> Params
;
16177 if (ExplicitSignature
) {
16178 for (unsigned I
= 0, E
= ExplicitSignature
.getNumParams(); I
!= E
; ++I
) {
16179 ParmVarDecl
*Param
= ExplicitSignature
.getParam(I
);
16180 if (Param
->getIdentifier() == nullptr && !Param
->isImplicit() &&
16181 !Param
->isInvalidDecl() && !getLangOpts().CPlusPlus
) {
16182 // Diagnose this as an extension in C17 and earlier.
16183 if (!getLangOpts().C23
)
16184 Diag(Param
->getLocation(), diag::ext_parameter_name_omitted_c23
);
16186 Params
.push_back(Param
);
16189 // Fake up parameter variables if we have a typedef, like
16190 // ^ fntype { ... }
16191 } else if (const FunctionProtoType
*Fn
= T
->getAs
<FunctionProtoType
>()) {
16192 for (const auto &I
: Fn
->param_types()) {
16193 ParmVarDecl
*Param
= BuildParmVarDeclForTypedef(
16194 CurBlock
->TheDecl
, ParamInfo
.getBeginLoc(), I
);
16195 Params
.push_back(Param
);
16199 // Set the parameters on the block decl.
16200 if (!Params
.empty()) {
16201 CurBlock
->TheDecl
->setParams(Params
);
16202 CheckParmsForFunctionDef(CurBlock
->TheDecl
->parameters(),
16203 /*CheckParameterNames=*/false);
16206 // Finally we can process decl attributes.
16207 ProcessDeclAttributes(CurScope
, CurBlock
->TheDecl
, ParamInfo
);
16209 // Put the parameter variables in scope.
16210 for (auto *AI
: CurBlock
->TheDecl
->parameters()) {
16211 AI
->setOwningFunction(CurBlock
->TheDecl
);
16213 // If this has an identifier, add it to the scope stack.
16214 if (AI
->getIdentifier()) {
16215 CheckShadow(CurBlock
->TheScope
, AI
);
16217 PushOnScopeChains(AI
, CurBlock
->TheScope
);
16220 if (AI
->isInvalidDecl())
16221 CurBlock
->TheDecl
->setInvalidDecl();
16225 void Sema::ActOnBlockError(SourceLocation CaretLoc
, Scope
*CurScope
) {
16226 // Leave the expression-evaluation context.
16227 DiscardCleanupsInEvaluationContext();
16228 PopExpressionEvaluationContext();
16230 // Pop off CurBlock, handle nested blocks.
16232 PopFunctionScopeInfo();
16235 ExprResult
Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc
,
16236 Stmt
*Body
, Scope
*CurScope
) {
16237 // If blocks are disabled, emit an error.
16238 if (!LangOpts
.Blocks
)
16239 Diag(CaretLoc
, diag::err_blocks_disable
) << LangOpts
.OpenCL
;
16241 // Leave the expression-evaluation context.
16242 if (hasAnyUnrecoverableErrorsInThisFunction())
16243 DiscardCleanupsInEvaluationContext();
16244 assert(!Cleanup
.exprNeedsCleanups() &&
16245 "cleanups within block not correctly bound!");
16246 PopExpressionEvaluationContext();
16248 BlockScopeInfo
*BSI
= cast
<BlockScopeInfo
>(FunctionScopes
.back());
16249 BlockDecl
*BD
= BSI
->TheDecl
;
16251 maybeAddDeclWithEffects(BD
);
16253 if (BSI
->HasImplicitReturnType
)
16254 deduceClosureReturnType(*BSI
);
16256 QualType RetTy
= Context
.VoidTy
;
16257 if (!BSI
->ReturnType
.isNull())
16258 RetTy
= BSI
->ReturnType
;
16260 bool NoReturn
= BD
->hasAttr
<NoReturnAttr
>();
16263 // If the user wrote a function type in some form, try to use that.
16264 if (!BSI
->FunctionType
.isNull()) {
16265 const FunctionType
*FTy
= BSI
->FunctionType
->castAs
<FunctionType
>();
16267 FunctionType::ExtInfo Ext
= FTy
->getExtInfo();
16268 if (NoReturn
&& !Ext
.getNoReturn()) Ext
= Ext
.withNoReturn(true);
16270 // Turn protoless block types into nullary block types.
16271 if (isa
<FunctionNoProtoType
>(FTy
)) {
16272 FunctionProtoType::ExtProtoInfo EPI
;
16274 BlockTy
= Context
.getFunctionType(RetTy
, {}, EPI
);
16276 // Otherwise, if we don't need to change anything about the function type,
16277 // preserve its sugar structure.
16278 } else if (FTy
->getReturnType() == RetTy
&&
16279 (!NoReturn
|| FTy
->getNoReturnAttr())) {
16280 BlockTy
= BSI
->FunctionType
;
16282 // Otherwise, make the minimal modifications to the function type.
16284 const FunctionProtoType
*FPT
= cast
<FunctionProtoType
>(FTy
);
16285 FunctionProtoType::ExtProtoInfo EPI
= FPT
->getExtProtoInfo();
16286 EPI
.TypeQuals
= Qualifiers();
16288 BlockTy
= Context
.getFunctionType(RetTy
, FPT
->getParamTypes(), EPI
);
16291 // If we don't have a function type, just build one from nothing.
16293 FunctionProtoType::ExtProtoInfo EPI
;
16294 EPI
.ExtInfo
= FunctionType::ExtInfo().withNoReturn(NoReturn
);
16295 BlockTy
= Context
.getFunctionType(RetTy
, {}, EPI
);
16298 DiagnoseUnusedParameters(BD
->parameters());
16299 BlockTy
= Context
.getBlockPointerType(BlockTy
);
16301 // If needed, diagnose invalid gotos and switches in the block.
16302 if (getCurFunction()->NeedsScopeChecking() &&
16303 !PP
.isCodeCompletionEnabled())
16304 DiagnoseInvalidJumps(cast
<CompoundStmt
>(Body
));
16306 BD
->setBody(cast
<CompoundStmt
>(Body
));
16308 if (Body
&& getCurFunction()->HasPotentialAvailabilityViolations
)
16309 DiagnoseUnguardedAvailabilityViolations(BD
);
16311 // Try to apply the named return value optimization. We have to check again
16312 // if we can do this, though, because blocks keep return statements around
16313 // to deduce an implicit return type.
16314 if (getLangOpts().CPlusPlus
&& RetTy
->isRecordType() &&
16315 !BD
->isDependentContext())
16316 computeNRVO(Body
, BSI
);
16318 if (RetTy
.hasNonTrivialToPrimitiveDestructCUnion() ||
16319 RetTy
.hasNonTrivialToPrimitiveCopyCUnion())
16320 checkNonTrivialCUnion(RetTy
, BD
->getCaretLocation(), NTCUC_FunctionReturn
,
16321 NTCUK_Destruct
|NTCUK_Copy
);
16325 // Set the captured variables on the block.
16326 SmallVector
<BlockDecl::Capture
, 4> Captures
;
16327 for (Capture
&Cap
: BSI
->Captures
) {
16328 if (Cap
.isInvalid() || Cap
.isThisCapture())
16330 // Cap.getVariable() is always a VarDecl because
16331 // blocks cannot capture structured bindings or other ValueDecl kinds.
16332 auto *Var
= cast
<VarDecl
>(Cap
.getVariable());
16333 Expr
*CopyExpr
= nullptr;
16334 if (getLangOpts().CPlusPlus
&& Cap
.isCopyCapture()) {
16335 if (const RecordType
*Record
=
16336 Cap
.getCaptureType()->getAs
<RecordType
>()) {
16337 // The capture logic needs the destructor, so make sure we mark it.
16338 // Usually this is unnecessary because most local variables have
16339 // their destructors marked at declaration time, but parameters are
16340 // an exception because it's technically only the call site that
16341 // actually requires the destructor.
16342 if (isa
<ParmVarDecl
>(Var
))
16343 FinalizeVarWithDestructor(Var
, Record
);
16345 // Enter a separate potentially-evaluated context while building block
16346 // initializers to isolate their cleanups from those of the block
16348 // FIXME: Is this appropriate even when the block itself occurs in an
16349 // unevaluated operand?
16350 EnterExpressionEvaluationContext
EvalContext(
16351 *this, ExpressionEvaluationContext::PotentiallyEvaluated
);
16353 SourceLocation Loc
= Cap
.getLocation();
16355 ExprResult Result
= BuildDeclarationNameExpr(
16356 CXXScopeSpec(), DeclarationNameInfo(Var
->getDeclName(), Loc
), Var
);
16358 // According to the blocks spec, the capture of a variable from
16359 // the stack requires a const copy constructor. This is not true
16360 // of the copy/move done to move a __block variable to the heap.
16361 if (!Result
.isInvalid() &&
16362 !Result
.get()->getType().isConstQualified()) {
16363 Result
= ImpCastExprToType(Result
.get(),
16364 Result
.get()->getType().withConst(),
16365 CK_NoOp
, VK_LValue
);
16368 if (!Result
.isInvalid()) {
16369 Result
= PerformCopyInitialization(
16370 InitializedEntity::InitializeBlock(Var
->getLocation(),
16371 Cap
.getCaptureType()),
16372 Loc
, Result
.get());
16375 // Build a full-expression copy expression if initialization
16376 // succeeded and used a non-trivial constructor. Recover from
16377 // errors by pretending that the copy isn't necessary.
16378 if (!Result
.isInvalid() &&
16379 !cast
<CXXConstructExpr
>(Result
.get())->getConstructor()
16381 Result
= MaybeCreateExprWithCleanups(Result
);
16382 CopyExpr
= Result
.get();
16387 BlockDecl::Capture
NewCap(Var
, Cap
.isBlockCapture(), Cap
.isNested(),
16389 Captures
.push_back(NewCap
);
16391 BD
->setCaptures(Context
, Captures
, BSI
->CXXThisCaptureIndex
!= 0);
16393 // Pop the block scope now but keep it alive to the end of this function.
16394 AnalysisBasedWarnings::Policy WP
= AnalysisWarnings
.getDefaultPolicy();
16395 PoppedFunctionScopePtr ScopeRAII
= PopFunctionScopeInfo(&WP
, BD
, BlockTy
);
16397 BlockExpr
*Result
= new (Context
)
16398 BlockExpr(BD
, BlockTy
, BSI
->ContainsUnexpandedParameterPack
);
16400 // If the block isn't obviously global, i.e. it captures anything at
16401 // all, then we need to do a few things in the surrounding context:
16402 if (Result
->getBlockDecl()->hasCaptures()) {
16403 // First, this expression has a new cleanup object.
16404 ExprCleanupObjects
.push_back(Result
->getBlockDecl());
16405 Cleanup
.setExprNeedsCleanups(true);
16407 // It also gets a branch-protected scope if any of the captured
16408 // variables needs destruction.
16409 for (const auto &CI
: Result
->getBlockDecl()->captures()) {
16410 const VarDecl
*var
= CI
.getVariable();
16411 if (var
->getType().isDestructedType() != QualType::DK_none
) {
16412 setFunctionHasBranchProtectedScope();
16418 if (getCurFunction())
16419 getCurFunction()->addBlock(BD
);
16421 // This can happen if the block's return type is deduced, but
16422 // the return expression is invalid.
16423 if (BD
->isInvalidDecl())
16424 return CreateRecoveryExpr(Result
->getBeginLoc(), Result
->getEndLoc(),
16425 {Result
}, Result
->getType());
16429 ExprResult
Sema::ActOnVAArg(SourceLocation BuiltinLoc
, Expr
*E
, ParsedType Ty
,
16430 SourceLocation RPLoc
) {
16431 TypeSourceInfo
*TInfo
;
16432 GetTypeFromParser(Ty
, &TInfo
);
16433 return BuildVAArgExpr(BuiltinLoc
, E
, TInfo
, RPLoc
);
16436 ExprResult
Sema::BuildVAArgExpr(SourceLocation BuiltinLoc
,
16437 Expr
*E
, TypeSourceInfo
*TInfo
,
16438 SourceLocation RPLoc
) {
16439 Expr
*OrigExpr
= E
;
16442 // CUDA device code does not support varargs.
16443 if (getLangOpts().CUDA
&& getLangOpts().CUDAIsDevice
) {
16444 if (const FunctionDecl
*F
= dyn_cast
<FunctionDecl
>(CurContext
)) {
16445 CUDAFunctionTarget T
= CUDA().IdentifyTarget(F
);
16446 if (T
== CUDAFunctionTarget::Global
|| T
== CUDAFunctionTarget::Device
||
16447 T
== CUDAFunctionTarget::HostDevice
)
16448 return ExprError(Diag(E
->getBeginLoc(), diag::err_va_arg_in_device
));
16452 // NVPTX does not support va_arg expression.
16453 if (getLangOpts().OpenMP
&& getLangOpts().OpenMPIsTargetDevice
&&
16454 Context
.getTargetInfo().getTriple().isNVPTX())
16455 targetDiag(E
->getBeginLoc(), diag::err_va_arg_in_device
);
16457 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16458 // as Microsoft ABI on an actual Microsoft platform, where
16459 // __builtin_ms_va_list and __builtin_va_list are the same.)
16460 if (!E
->isTypeDependent() && Context
.getTargetInfo().hasBuiltinMSVaList() &&
16461 Context
.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList
) {
16462 QualType MSVaListType
= Context
.getBuiltinMSVaListType();
16463 if (Context
.hasSameType(MSVaListType
, E
->getType())) {
16464 if (CheckForModifiableLvalue(E
, BuiltinLoc
, *this))
16465 return ExprError();
16470 // Get the va_list type
16471 QualType VaListType
= Context
.getBuiltinVaListType();
16473 if (VaListType
->isArrayType()) {
16474 // Deal with implicit array decay; for example, on x86-64,
16475 // va_list is an array, but it's supposed to decay to
16476 // a pointer for va_arg.
16477 VaListType
= Context
.getArrayDecayedType(VaListType
);
16478 // Make sure the input expression also decays appropriately.
16479 ExprResult Result
= UsualUnaryConversions(E
);
16480 if (Result
.isInvalid())
16481 return ExprError();
16483 } else if (VaListType
->isRecordType() && getLangOpts().CPlusPlus
) {
16484 // If va_list is a record type and we are compiling in C++ mode,
16485 // check the argument using reference binding.
16486 InitializedEntity Entity
= InitializedEntity::InitializeParameter(
16487 Context
, Context
.getLValueReferenceType(VaListType
), false);
16488 ExprResult Init
= PerformCopyInitialization(Entity
, SourceLocation(), E
);
16489 if (Init
.isInvalid())
16490 return ExprError();
16491 E
= Init
.getAs
<Expr
>();
16493 // Otherwise, the va_list argument must be an l-value because
16494 // it is modified by va_arg.
16495 if (!E
->isTypeDependent() &&
16496 CheckForModifiableLvalue(E
, BuiltinLoc
, *this))
16497 return ExprError();
16501 if (!IsMS
&& !E
->isTypeDependent() &&
16502 !Context
.hasSameType(VaListType
, E
->getType()))
16504 Diag(E
->getBeginLoc(),
16505 diag::err_first_argument_to_va_arg_not_of_type_va_list
)
16506 << OrigExpr
->getType() << E
->getSourceRange());
16508 if (!TInfo
->getType()->isDependentType()) {
16509 if (RequireCompleteType(TInfo
->getTypeLoc().getBeginLoc(), TInfo
->getType(),
16510 diag::err_second_parameter_to_va_arg_incomplete
,
16511 TInfo
->getTypeLoc()))
16512 return ExprError();
16514 if (RequireNonAbstractType(TInfo
->getTypeLoc().getBeginLoc(),
16516 diag::err_second_parameter_to_va_arg_abstract
,
16517 TInfo
->getTypeLoc()))
16518 return ExprError();
16520 if (!TInfo
->getType().isPODType(Context
)) {
16521 Diag(TInfo
->getTypeLoc().getBeginLoc(),
16522 TInfo
->getType()->isObjCLifetimeType()
16523 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16524 : diag::warn_second_parameter_to_va_arg_not_pod
)
16525 << TInfo
->getType()
16526 << TInfo
->getTypeLoc().getSourceRange();
16529 // Check for va_arg where arguments of the given type will be promoted
16530 // (i.e. this va_arg is guaranteed to have undefined behavior).
16531 QualType PromoteType
;
16532 if (Context
.isPromotableIntegerType(TInfo
->getType())) {
16533 PromoteType
= Context
.getPromotedIntegerType(TInfo
->getType());
16534 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16535 // and C23 7.16.1.1p2 says, in part:
16536 // If type is not compatible with the type of the actual next argument
16537 // (as promoted according to the default argument promotions), the
16538 // behavior is undefined, except for the following cases:
16539 // - both types are pointers to qualified or unqualified versions of
16540 // compatible types;
16541 // - one type is compatible with a signed integer type, the other
16542 // type is compatible with the corresponding unsigned integer type,
16543 // and the value is representable in both types;
16544 // - one type is pointer to qualified or unqualified void and the
16545 // other is a pointer to a qualified or unqualified character type;
16546 // - or, the type of the next argument is nullptr_t and type is a
16547 // pointer type that has the same representation and alignment
16548 // requirements as a pointer to a character type.
16549 // Given that type compatibility is the primary requirement (ignoring
16550 // qualifications), you would think we could call typesAreCompatible()
16551 // directly to test this. However, in C++, that checks for *same type*,
16552 // which causes false positives when passing an enumeration type to
16553 // va_arg. Instead, get the underlying type of the enumeration and pass
16555 QualType UnderlyingType
= TInfo
->getType();
16556 if (const auto *ET
= UnderlyingType
->getAs
<EnumType
>())
16557 UnderlyingType
= ET
->getDecl()->getIntegerType();
16558 if (Context
.typesAreCompatible(PromoteType
, UnderlyingType
,
16559 /*CompareUnqualified*/ true))
16560 PromoteType
= QualType();
16562 // If the types are still not compatible, we need to test whether the
16563 // promoted type and the underlying type are the same except for
16564 // signedness. Ask the AST for the correctly corresponding type and see
16565 // if that's compatible.
16566 if (!PromoteType
.isNull() && !UnderlyingType
->isBooleanType() &&
16567 PromoteType
->isUnsignedIntegerType() !=
16568 UnderlyingType
->isUnsignedIntegerType()) {
16570 UnderlyingType
->isUnsignedIntegerType()
16571 ? Context
.getCorrespondingSignedType(UnderlyingType
)
16572 : Context
.getCorrespondingUnsignedType(UnderlyingType
);
16573 if (Context
.typesAreCompatible(PromoteType
, UnderlyingType
,
16574 /*CompareUnqualified*/ true))
16575 PromoteType
= QualType();
16578 if (TInfo
->getType()->isSpecificBuiltinType(BuiltinType::Float
))
16579 PromoteType
= Context
.DoubleTy
;
16580 if (!PromoteType
.isNull())
16581 DiagRuntimeBehavior(TInfo
->getTypeLoc().getBeginLoc(), E
,
16582 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible
)
16583 << TInfo
->getType()
16585 << TInfo
->getTypeLoc().getSourceRange());
16588 QualType T
= TInfo
->getType().getNonLValueExprType(Context
);
16589 return new (Context
) VAArgExpr(BuiltinLoc
, E
, TInfo
, RPLoc
, T
, IsMS
);
16592 ExprResult
Sema::ActOnGNUNullExpr(SourceLocation TokenLoc
) {
16593 // The type of __null will be int or long, depending on the size of
16594 // pointers on the target.
16596 unsigned pw
= Context
.getTargetInfo().getPointerWidth(LangAS::Default
);
16597 if (pw
== Context
.getTargetInfo().getIntWidth())
16598 Ty
= Context
.IntTy
;
16599 else if (pw
== Context
.getTargetInfo().getLongWidth())
16600 Ty
= Context
.LongTy
;
16601 else if (pw
== Context
.getTargetInfo().getLongLongWidth())
16602 Ty
= Context
.LongLongTy
;
16604 llvm_unreachable("I don't know size of pointer!");
16607 return new (Context
) GNUNullExpr(Ty
, TokenLoc
);
16610 static CXXRecordDecl
*LookupStdSourceLocationImpl(Sema
&S
, SourceLocation Loc
) {
16611 CXXRecordDecl
*ImplDecl
= nullptr;
16613 // Fetch the std::source_location::__impl decl.
16614 if (NamespaceDecl
*Std
= S
.getStdNamespace()) {
16615 LookupResult
ResultSL(S
, &S
.PP
.getIdentifierTable().get("source_location"),
16616 Loc
, Sema::LookupOrdinaryName
);
16617 if (S
.LookupQualifiedName(ResultSL
, Std
)) {
16618 if (auto *SLDecl
= ResultSL
.getAsSingle
<RecordDecl
>()) {
16619 LookupResult
ResultImpl(S
, &S
.PP
.getIdentifierTable().get("__impl"),
16620 Loc
, Sema::LookupOrdinaryName
);
16621 if ((SLDecl
->isCompleteDefinition() || SLDecl
->isBeingDefined()) &&
16622 S
.LookupQualifiedName(ResultImpl
, SLDecl
)) {
16623 ImplDecl
= ResultImpl
.getAsSingle
<CXXRecordDecl
>();
16629 if (!ImplDecl
|| !ImplDecl
->isCompleteDefinition()) {
16630 S
.Diag(Loc
, diag::err_std_source_location_impl_not_found
);
16634 // Verify that __impl is a trivial struct type, with no base classes, and with
16635 // only the four expected fields.
16636 if (ImplDecl
->isUnion() || !ImplDecl
->isStandardLayout() ||
16637 ImplDecl
->getNumBases() != 0) {
16638 S
.Diag(Loc
, diag::err_std_source_location_impl_malformed
);
16642 unsigned Count
= 0;
16643 for (FieldDecl
*F
: ImplDecl
->fields()) {
16644 StringRef Name
= F
->getName();
16646 if (Name
== "_M_file_name") {
16647 if (F
->getType() !=
16648 S
.Context
.getPointerType(S
.Context
.CharTy
.withConst()))
16651 } else if (Name
== "_M_function_name") {
16652 if (F
->getType() !=
16653 S
.Context
.getPointerType(S
.Context
.CharTy
.withConst()))
16656 } else if (Name
== "_M_line") {
16657 if (!F
->getType()->isIntegerType())
16660 } else if (Name
== "_M_column") {
16661 if (!F
->getType()->isIntegerType())
16665 Count
= 100; // invalid
16670 S
.Diag(Loc
, diag::err_std_source_location_impl_malformed
);
16677 ExprResult
Sema::ActOnSourceLocExpr(SourceLocIdentKind Kind
,
16678 SourceLocation BuiltinLoc
,
16679 SourceLocation RPLoc
) {
16682 case SourceLocIdentKind::File
:
16683 case SourceLocIdentKind::FileName
:
16684 case SourceLocIdentKind::Function
:
16685 case SourceLocIdentKind::FuncSig
: {
16686 QualType ArrTy
= Context
.getStringLiteralArrayType(Context
.CharTy
, 0);
16688 Context
.getPointerType(ArrTy
->getAsArrayTypeUnsafe()->getElementType());
16691 case SourceLocIdentKind::Line
:
16692 case SourceLocIdentKind::Column
:
16693 ResultTy
= Context
.UnsignedIntTy
;
16695 case SourceLocIdentKind::SourceLocStruct
:
16696 if (!StdSourceLocationImplDecl
) {
16697 StdSourceLocationImplDecl
=
16698 LookupStdSourceLocationImpl(*this, BuiltinLoc
);
16699 if (!StdSourceLocationImplDecl
)
16700 return ExprError();
16702 ResultTy
= Context
.getPointerType(
16703 Context
.getRecordType(StdSourceLocationImplDecl
).withConst());
16707 return BuildSourceLocExpr(Kind
, ResultTy
, BuiltinLoc
, RPLoc
, CurContext
);
16710 ExprResult
Sema::BuildSourceLocExpr(SourceLocIdentKind Kind
, QualType ResultTy
,
16711 SourceLocation BuiltinLoc
,
16712 SourceLocation RPLoc
,
16713 DeclContext
*ParentContext
) {
16714 return new (Context
)
16715 SourceLocExpr(Context
, Kind
, ResultTy
, BuiltinLoc
, RPLoc
, ParentContext
);
16718 ExprResult
Sema::ActOnEmbedExpr(SourceLocation EmbedKeywordLoc
,
16719 StringLiteral
*BinaryData
) {
16720 EmbedDataStorage
*Data
= new (Context
) EmbedDataStorage
;
16721 Data
->BinaryData
= BinaryData
;
16722 return new (Context
)
16723 EmbedExpr(Context
, EmbedKeywordLoc
, Data
, /*NumOfElements=*/0,
16724 Data
->getDataElementCount());
16727 static bool maybeDiagnoseAssignmentToFunction(Sema
&S
, QualType DstType
,
16728 const Expr
*SrcExpr
) {
16729 if (!DstType
->isFunctionPointerType() ||
16730 !SrcExpr
->getType()->isFunctionType())
16733 auto *DRE
= dyn_cast
<DeclRefExpr
>(SrcExpr
->IgnoreParenImpCasts());
16737 auto *FD
= dyn_cast
<FunctionDecl
>(DRE
->getDecl());
16741 return !S
.checkAddressOfFunctionIsAvailable(FD
,
16743 SrcExpr
->getBeginLoc());
16746 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy
,
16747 SourceLocation Loc
,
16748 QualType DstType
, QualType SrcType
,
16749 Expr
*SrcExpr
, AssignmentAction Action
,
16750 bool *Complained
) {
16752 *Complained
= false;
16754 // Decode the result (notice that AST's are still created for extensions).
16755 bool CheckInferredResultType
= false;
16756 bool isInvalid
= false;
16757 unsigned DiagKind
= 0;
16758 ConversionFixItGenerator ConvHints
;
16759 bool MayHaveConvFixit
= false;
16760 bool MayHaveFunctionDiff
= false;
16761 const ObjCInterfaceDecl
*IFace
= nullptr;
16762 const ObjCProtocolDecl
*PDecl
= nullptr;
16766 DiagnoseAssignmentEnum(DstType
, SrcType
, SrcExpr
);
16770 if (getLangOpts().CPlusPlus
) {
16771 DiagKind
= diag::err_typecheck_convert_pointer_int
;
16774 DiagKind
= diag::ext_typecheck_convert_pointer_int
;
16776 ConvHints
.tryToFixConversion(SrcExpr
, SrcType
, DstType
, *this);
16777 MayHaveConvFixit
= true;
16780 if (getLangOpts().CPlusPlus
) {
16781 DiagKind
= diag::err_typecheck_convert_int_pointer
;
16784 DiagKind
= diag::ext_typecheck_convert_int_pointer
;
16786 ConvHints
.tryToFixConversion(SrcExpr
, SrcType
, DstType
, *this);
16787 MayHaveConvFixit
= true;
16789 case IncompatibleFunctionPointerStrict
:
16791 diag::warn_typecheck_convert_incompatible_function_pointer_strict
;
16792 ConvHints
.tryToFixConversion(SrcExpr
, SrcType
, DstType
, *this);
16793 MayHaveConvFixit
= true;
16795 case IncompatibleFunctionPointer
:
16796 if (getLangOpts().CPlusPlus
) {
16797 DiagKind
= diag::err_typecheck_convert_incompatible_function_pointer
;
16800 DiagKind
= diag::ext_typecheck_convert_incompatible_function_pointer
;
16802 ConvHints
.tryToFixConversion(SrcExpr
, SrcType
, DstType
, *this);
16803 MayHaveConvFixit
= true;
16805 case IncompatiblePointer
:
16806 if (Action
== AssignmentAction::Passing_CFAudited
) {
16807 DiagKind
= diag::err_arc_typecheck_convert_incompatible_pointer
;
16808 } else if (getLangOpts().CPlusPlus
) {
16809 DiagKind
= diag::err_typecheck_convert_incompatible_pointer
;
16812 DiagKind
= diag::ext_typecheck_convert_incompatible_pointer
;
16814 CheckInferredResultType
= DstType
->isObjCObjectPointerType() &&
16815 SrcType
->isObjCObjectPointerType();
16816 if (CheckInferredResultType
) {
16817 SrcType
= SrcType
.getUnqualifiedType();
16818 DstType
= DstType
.getUnqualifiedType();
16820 ConvHints
.tryToFixConversion(SrcExpr
, SrcType
, DstType
, *this);
16822 MayHaveConvFixit
= true;
16824 case IncompatiblePointerSign
:
16825 if (getLangOpts().CPlusPlus
) {
16826 DiagKind
= diag::err_typecheck_convert_incompatible_pointer_sign
;
16829 DiagKind
= diag::ext_typecheck_convert_incompatible_pointer_sign
;
16832 case FunctionVoidPointer
:
16833 if (getLangOpts().CPlusPlus
) {
16834 DiagKind
= diag::err_typecheck_convert_pointer_void_func
;
16837 DiagKind
= diag::ext_typecheck_convert_pointer_void_func
;
16840 case IncompatiblePointerDiscardsQualifiers
: {
16841 // Perform array-to-pointer decay if necessary.
16842 if (SrcType
->isArrayType()) SrcType
= Context
.getArrayDecayedType(SrcType
);
16846 Qualifiers lhq
= SrcType
->getPointeeType().getQualifiers();
16847 Qualifiers rhq
= DstType
->getPointeeType().getQualifiers();
16848 if (lhq
.getAddressSpace() != rhq
.getAddressSpace()) {
16849 DiagKind
= diag::err_typecheck_incompatible_address_space
;
16851 } else if (lhq
.getObjCLifetime() != rhq
.getObjCLifetime()) {
16852 DiagKind
= diag::err_typecheck_incompatible_ownership
;
16856 llvm_unreachable("unknown error case for discarding qualifiers!");
16859 case CompatiblePointerDiscardsQualifiers
:
16860 // If the qualifiers lost were because we were applying the
16861 // (deprecated) C++ conversion from a string literal to a char*
16862 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
16863 // Ideally, this check would be performed in
16864 // checkPointerTypesForAssignment. However, that would require a
16865 // bit of refactoring (so that the second argument is an
16866 // expression, rather than a type), which should be done as part
16867 // of a larger effort to fix checkPointerTypesForAssignment for
16869 if (getLangOpts().CPlusPlus
&&
16870 IsStringLiteralToNonConstPointerConversion(SrcExpr
, DstType
))
16872 if (getLangOpts().CPlusPlus
) {
16873 DiagKind
= diag::err_typecheck_convert_discards_qualifiers
;
16876 DiagKind
= diag::ext_typecheck_convert_discards_qualifiers
;
16880 case IncompatibleNestedPointerQualifiers
:
16881 if (getLangOpts().CPlusPlus
) {
16883 DiagKind
= diag::err_nested_pointer_qualifier_mismatch
;
16885 DiagKind
= diag::ext_nested_pointer_qualifier_mismatch
;
16888 case IncompatibleNestedPointerAddressSpaceMismatch
:
16889 DiagKind
= diag::err_typecheck_incompatible_nested_address_space
;
16892 case IntToBlockPointer
:
16893 DiagKind
= diag::err_int_to_block_pointer
;
16896 case IncompatibleBlockPointer
:
16897 DiagKind
= diag::err_typecheck_convert_incompatible_block_pointer
;
16900 case IncompatibleObjCQualifiedId
: {
16901 if (SrcType
->isObjCQualifiedIdType()) {
16902 const ObjCObjectPointerType
*srcOPT
=
16903 SrcType
->castAs
<ObjCObjectPointerType
>();
16904 for (auto *srcProto
: srcOPT
->quals()) {
16908 if (const ObjCInterfaceType
*IFaceT
=
16909 DstType
->castAs
<ObjCObjectPointerType
>()->getInterfaceType())
16910 IFace
= IFaceT
->getDecl();
16912 else if (DstType
->isObjCQualifiedIdType()) {
16913 const ObjCObjectPointerType
*dstOPT
=
16914 DstType
->castAs
<ObjCObjectPointerType
>();
16915 for (auto *dstProto
: dstOPT
->quals()) {
16919 if (const ObjCInterfaceType
*IFaceT
=
16920 SrcType
->castAs
<ObjCObjectPointerType
>()->getInterfaceType())
16921 IFace
= IFaceT
->getDecl();
16923 if (getLangOpts().CPlusPlus
) {
16924 DiagKind
= diag::err_incompatible_qualified_id
;
16927 DiagKind
= diag::warn_incompatible_qualified_id
;
16931 case IncompatibleVectors
:
16932 if (getLangOpts().CPlusPlus
) {
16933 DiagKind
= diag::err_incompatible_vectors
;
16936 DiagKind
= diag::warn_incompatible_vectors
;
16939 case IncompatibleObjCWeakRef
:
16940 DiagKind
= diag::err_arc_weak_unavailable_assign
;
16944 if (maybeDiagnoseAssignmentToFunction(*this, DstType
, SrcExpr
)) {
16946 *Complained
= true;
16950 DiagKind
= diag::err_typecheck_convert_incompatible
;
16951 ConvHints
.tryToFixConversion(SrcExpr
, SrcType
, DstType
, *this);
16952 MayHaveConvFixit
= true;
16954 MayHaveFunctionDiff
= true;
16958 QualType FirstType
, SecondType
;
16960 case AssignmentAction::Assigning
:
16961 case AssignmentAction::Initializing
:
16962 // The destination type comes first.
16963 FirstType
= DstType
;
16964 SecondType
= SrcType
;
16967 case AssignmentAction::Returning
:
16968 case AssignmentAction::Passing
:
16969 case AssignmentAction::Passing_CFAudited
:
16970 case AssignmentAction::Converting
:
16971 case AssignmentAction::Sending
:
16972 case AssignmentAction::Casting
:
16973 // The source type comes first.
16974 FirstType
= SrcType
;
16975 SecondType
= DstType
;
16979 PartialDiagnostic FDiag
= PDiag(DiagKind
);
16980 AssignmentAction ActionForDiag
= Action
;
16981 if (Action
== AssignmentAction::Passing_CFAudited
)
16982 ActionForDiag
= AssignmentAction::Passing
;
16984 FDiag
<< FirstType
<< SecondType
<< ActionForDiag
16985 << SrcExpr
->getSourceRange();
16987 if (DiagKind
== diag::ext_typecheck_convert_incompatible_pointer_sign
||
16988 DiagKind
== diag::err_typecheck_convert_incompatible_pointer_sign
) {
16989 auto isPlainChar
= [](const clang::Type
*Type
) {
16990 return Type
->isSpecificBuiltinType(BuiltinType::Char_S
) ||
16991 Type
->isSpecificBuiltinType(BuiltinType::Char_U
);
16993 FDiag
<< (isPlainChar(FirstType
->getPointeeOrArrayElementType()) ||
16994 isPlainChar(SecondType
->getPointeeOrArrayElementType()));
16997 // If we can fix the conversion, suggest the FixIts.
16998 if (!ConvHints
.isNull()) {
16999 for (FixItHint
&H
: ConvHints
.Hints
)
17003 if (MayHaveConvFixit
) { FDiag
<< (unsigned) (ConvHints
.Kind
); }
17005 if (MayHaveFunctionDiff
)
17006 HandleFunctionTypeMismatch(FDiag
, SecondType
, FirstType
);
17009 if ((DiagKind
== diag::warn_incompatible_qualified_id
||
17010 DiagKind
== diag::err_incompatible_qualified_id
) &&
17011 PDecl
&& IFace
&& !IFace
->hasDefinition())
17012 Diag(IFace
->getLocation(), diag::note_incomplete_class_and_qualified_id
)
17015 if (SecondType
== Context
.OverloadTy
)
17016 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr
).Expression
,
17017 FirstType
, /*TakingAddress=*/true);
17019 if (CheckInferredResultType
)
17020 ObjC().EmitRelatedResultTypeNote(SrcExpr
);
17022 if (Action
== AssignmentAction::Returning
&& ConvTy
== IncompatiblePointer
)
17023 ObjC().EmitRelatedResultTypeNoteForReturn(DstType
);
17026 *Complained
= true;
17030 ExprResult
Sema::VerifyIntegerConstantExpression(Expr
*E
,
17031 llvm::APSInt
*Result
,
17032 AllowFoldKind CanFold
) {
17033 class SimpleICEDiagnoser
: public VerifyICEDiagnoser
{
17035 SemaDiagnosticBuilder
diagnoseNotICEType(Sema
&S
, SourceLocation Loc
,
17036 QualType T
) override
{
17037 return S
.Diag(Loc
, diag::err_ice_not_integral
)
17038 << T
<< S
.LangOpts
.CPlusPlus
;
17040 SemaDiagnosticBuilder
diagnoseNotICE(Sema
&S
, SourceLocation Loc
) override
{
17041 return S
.Diag(Loc
, diag::err_expr_not_ice
) << S
.LangOpts
.CPlusPlus
;
17045 return VerifyIntegerConstantExpression(E
, Result
, Diagnoser
, CanFold
);
17048 ExprResult
Sema::VerifyIntegerConstantExpression(Expr
*E
,
17049 llvm::APSInt
*Result
,
17051 AllowFoldKind CanFold
) {
17052 class IDDiagnoser
: public VerifyICEDiagnoser
{
17056 IDDiagnoser(unsigned DiagID
)
17057 : VerifyICEDiagnoser(DiagID
== 0), DiagID(DiagID
) { }
17059 SemaDiagnosticBuilder
diagnoseNotICE(Sema
&S
, SourceLocation Loc
) override
{
17060 return S
.Diag(Loc
, DiagID
);
17062 } Diagnoser(DiagID
);
17064 return VerifyIntegerConstantExpression(E
, Result
, Diagnoser
, CanFold
);
17067 Sema::SemaDiagnosticBuilder
17068 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema
&S
, SourceLocation Loc
,
17070 return diagnoseNotICE(S
, Loc
);
17073 Sema::SemaDiagnosticBuilder
17074 Sema::VerifyICEDiagnoser::diagnoseFold(Sema
&S
, SourceLocation Loc
) {
17075 return S
.Diag(Loc
, diag::ext_expr_not_ice
) << S
.LangOpts
.CPlusPlus
;
17079 Sema::VerifyIntegerConstantExpression(Expr
*E
, llvm::APSInt
*Result
,
17080 VerifyICEDiagnoser
&Diagnoser
,
17081 AllowFoldKind CanFold
) {
17082 SourceLocation DiagLoc
= E
->getBeginLoc();
17084 if (getLangOpts().CPlusPlus11
) {
17085 // C++11 [expr.const]p5:
17086 // If an expression of literal class type is used in a context where an
17087 // integral constant expression is required, then that class type shall
17088 // have a single non-explicit conversion function to an integral or
17089 // unscoped enumeration type
17090 ExprResult Converted
;
17091 class CXX11ConvertDiagnoser
: public ICEConvertDiagnoser
{
17092 VerifyICEDiagnoser
&BaseDiagnoser
;
17094 CXX11ConvertDiagnoser(VerifyICEDiagnoser
&BaseDiagnoser
)
17095 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17096 BaseDiagnoser
.Suppress
, true),
17097 BaseDiagnoser(BaseDiagnoser
) {}
17099 SemaDiagnosticBuilder
diagnoseNotInt(Sema
&S
, SourceLocation Loc
,
17100 QualType T
) override
{
17101 return BaseDiagnoser
.diagnoseNotICEType(S
, Loc
, T
);
17104 SemaDiagnosticBuilder
diagnoseIncomplete(
17105 Sema
&S
, SourceLocation Loc
, QualType T
) override
{
17106 return S
.Diag(Loc
, diag::err_ice_incomplete_type
) << T
;
17109 SemaDiagnosticBuilder
diagnoseExplicitConv(
17110 Sema
&S
, SourceLocation Loc
, QualType T
, QualType ConvTy
) override
{
17111 return S
.Diag(Loc
, diag::err_ice_explicit_conversion
) << T
<< ConvTy
;
17114 SemaDiagnosticBuilder
noteExplicitConv(
17115 Sema
&S
, CXXConversionDecl
*Conv
, QualType ConvTy
) override
{
17116 return S
.Diag(Conv
->getLocation(), diag::note_ice_conversion_here
)
17117 << ConvTy
->isEnumeralType() << ConvTy
;
17120 SemaDiagnosticBuilder
diagnoseAmbiguous(
17121 Sema
&S
, SourceLocation Loc
, QualType T
) override
{
17122 return S
.Diag(Loc
, diag::err_ice_ambiguous_conversion
) << T
;
17125 SemaDiagnosticBuilder
noteAmbiguous(
17126 Sema
&S
, CXXConversionDecl
*Conv
, QualType ConvTy
) override
{
17127 return S
.Diag(Conv
->getLocation(), diag::note_ice_conversion_here
)
17128 << ConvTy
->isEnumeralType() << ConvTy
;
17131 SemaDiagnosticBuilder
diagnoseConversion(
17132 Sema
&S
, SourceLocation Loc
, QualType T
, QualType ConvTy
) override
{
17133 llvm_unreachable("conversion functions are permitted");
17135 } ConvertDiagnoser(Diagnoser
);
17137 Converted
= PerformContextualImplicitConversion(DiagLoc
, E
,
17139 if (Converted
.isInvalid())
17141 E
= Converted
.get();
17142 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
17143 // don't try to evaluate it later. We also don't want to return the
17144 // RecoveryExpr here, as it results in this call succeeding, thus callers of
17145 // this function will attempt to use 'Value'.
17146 if (isa
<RecoveryExpr
>(E
))
17147 return ExprError();
17148 if (!E
->getType()->isIntegralOrUnscopedEnumerationType())
17149 return ExprError();
17150 } else if (!E
->getType()->isIntegralOrUnscopedEnumerationType()) {
17151 // An ICE must be of integral or unscoped enumeration type.
17152 if (!Diagnoser
.Suppress
)
17153 Diagnoser
.diagnoseNotICEType(*this, DiagLoc
, E
->getType())
17154 << E
->getSourceRange();
17155 return ExprError();
17158 ExprResult RValueExpr
= DefaultLvalueConversion(E
);
17159 if (RValueExpr
.isInvalid())
17160 return ExprError();
17162 E
= RValueExpr
.get();
17164 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17165 // in the non-ICE case.
17166 if (!getLangOpts().CPlusPlus11
&& E
->isIntegerConstantExpr(Context
)) {
17167 SmallVector
<PartialDiagnosticAt
, 8> Notes
;
17169 *Result
= E
->EvaluateKnownConstIntCheckOverflow(Context
, &Notes
);
17170 if (!isa
<ConstantExpr
>(E
))
17171 E
= Result
? ConstantExpr::Create(Context
, E
, APValue(*Result
))
17172 : ConstantExpr::Create(Context
, E
);
17177 // If our only note is the usual "invalid subexpression" note, just point
17178 // the caret at its location rather than producing an essentially
17180 if (Notes
.size() == 1 && Notes
[0].second
.getDiagID() ==
17181 diag::note_invalid_subexpr_in_const_expr
) {
17182 DiagLoc
= Notes
[0].first
;
17186 if (getLangOpts().CPlusPlus
) {
17187 if (!Diagnoser
.Suppress
) {
17188 Diagnoser
.diagnoseNotICE(*this, DiagLoc
) << E
->getSourceRange();
17189 for (const PartialDiagnosticAt
&Note
: Notes
)
17190 Diag(Note
.first
, Note
.second
);
17192 return ExprError();
17195 Diagnoser
.diagnoseFold(*this, DiagLoc
) << E
->getSourceRange();
17196 for (const PartialDiagnosticAt
&Note
: Notes
)
17197 Diag(Note
.first
, Note
.second
);
17202 Expr::EvalResult EvalResult
;
17203 SmallVector
<PartialDiagnosticAt
, 8> Notes
;
17204 EvalResult
.Diag
= &Notes
;
17206 // Try to evaluate the expression, and produce diagnostics explaining why it's
17207 // not a constant expression as a side-effect.
17209 E
->EvaluateAsRValue(EvalResult
, Context
, /*isConstantContext*/ true) &&
17210 EvalResult
.Val
.isInt() && !EvalResult
.HasSideEffects
&&
17211 (!getLangOpts().CPlusPlus
|| !EvalResult
.HasUndefinedBehavior
);
17213 if (!isa
<ConstantExpr
>(E
))
17214 E
= ConstantExpr::Create(Context
, E
, EvalResult
.Val
);
17216 // In C++11, we can rely on diagnostics being produced for any expression
17217 // which is not a constant expression. If no diagnostics were produced, then
17218 // this is a constant expression.
17219 if (Folded
&& getLangOpts().CPlusPlus11
&& Notes
.empty()) {
17221 *Result
= EvalResult
.Val
.getInt();
17225 // If our only note is the usual "invalid subexpression" note, just point
17226 // the caret at its location rather than producing an essentially
17228 if (Notes
.size() == 1 && Notes
[0].second
.getDiagID() ==
17229 diag::note_invalid_subexpr_in_const_expr
) {
17230 DiagLoc
= Notes
[0].first
;
17234 if (!Folded
|| !CanFold
) {
17235 if (!Diagnoser
.Suppress
) {
17236 Diagnoser
.diagnoseNotICE(*this, DiagLoc
) << E
->getSourceRange();
17237 for (const PartialDiagnosticAt
&Note
: Notes
)
17238 Diag(Note
.first
, Note
.second
);
17241 return ExprError();
17244 Diagnoser
.diagnoseFold(*this, DiagLoc
) << E
->getSourceRange();
17245 for (const PartialDiagnosticAt
&Note
: Notes
)
17246 Diag(Note
.first
, Note
.second
);
17249 *Result
= EvalResult
.Val
.getInt();
17254 // Handle the case where we conclude a expression which we speculatively
17255 // considered to be unevaluated is actually evaluated.
17256 class TransformToPE
: public TreeTransform
<TransformToPE
> {
17257 typedef TreeTransform
<TransformToPE
> BaseTransform
;
17260 TransformToPE(Sema
&SemaRef
) : BaseTransform(SemaRef
) { }
17262 // Make sure we redo semantic analysis
17263 bool AlwaysRebuild() { return true; }
17264 bool ReplacingOriginal() { return true; }
17266 // We need to special-case DeclRefExprs referring to FieldDecls which
17267 // are not part of a member pointer formation; normal TreeTransforming
17268 // doesn't catch this case because of the way we represent them in the AST.
17269 // FIXME: This is a bit ugly; is it really the best way to handle this
17272 // Error on DeclRefExprs referring to FieldDecls.
17273 ExprResult
TransformDeclRefExpr(DeclRefExpr
*E
) {
17274 if (isa
<FieldDecl
>(E
->getDecl()) &&
17275 !SemaRef
.isUnevaluatedContext())
17276 return SemaRef
.Diag(E
->getLocation(),
17277 diag::err_invalid_non_static_member_use
)
17278 << E
->getDecl() << E
->getSourceRange();
17280 return BaseTransform::TransformDeclRefExpr(E
);
17283 // Exception: filter out member pointer formation
17284 ExprResult
TransformUnaryOperator(UnaryOperator
*E
) {
17285 if (E
->getOpcode() == UO_AddrOf
&& E
->getType()->isMemberPointerType())
17288 return BaseTransform::TransformUnaryOperator(E
);
17291 // The body of a lambda-expression is in a separate expression evaluation
17292 // context so never needs to be transformed.
17293 // FIXME: Ideally we wouldn't transform the closure type either, and would
17294 // just recreate the capture expressions and lambda expression.
17295 StmtResult
TransformLambdaBody(LambdaExpr
*E
, Stmt
*Body
) {
17296 return SkipLambdaBody(E
, Body
);
17301 ExprResult
Sema::TransformToPotentiallyEvaluated(Expr
*E
) {
17302 assert(isUnevaluatedContext() &&
17303 "Should only transform unevaluated expressions");
17304 ExprEvalContexts
.back().Context
=
17305 ExprEvalContexts
[ExprEvalContexts
.size()-2].Context
;
17306 if (isUnevaluatedContext())
17308 return TransformToPE(*this).TransformExpr(E
);
17311 TypeSourceInfo
*Sema::TransformToPotentiallyEvaluated(TypeSourceInfo
*TInfo
) {
17312 assert(isUnevaluatedContext() &&
17313 "Should only transform unevaluated expressions");
17314 ExprEvalContexts
.back().Context
= parentEvaluationContext().Context
;
17315 if (isUnevaluatedContext())
17317 return TransformToPE(*this).TransformType(TInfo
);
17321 Sema::PushExpressionEvaluationContext(
17322 ExpressionEvaluationContext NewContext
, Decl
*LambdaContextDecl
,
17323 ExpressionEvaluationContextRecord::ExpressionKind ExprContext
) {
17324 ExprEvalContexts
.emplace_back(NewContext
, ExprCleanupObjects
.size(), Cleanup
,
17325 LambdaContextDecl
, ExprContext
);
17327 // Discarded statements and immediate contexts nested in other
17328 // discarded statements or immediate context are themselves
17329 // a discarded statement or an immediate context, respectively.
17330 ExprEvalContexts
.back().InDiscardedStatement
=
17331 parentEvaluationContext().isDiscardedStatementContext();
17333 // C++23 [expr.const]/p15
17334 // An expression or conversion is in an immediate function context if [...]
17335 // it is a subexpression of a manifestly constant-evaluated expression or
17337 const auto &Prev
= parentEvaluationContext();
17338 ExprEvalContexts
.back().InImmediateFunctionContext
=
17339 Prev
.isImmediateFunctionContext() || Prev
.isConstantEvaluated();
17341 ExprEvalContexts
.back().InImmediateEscalatingFunctionContext
=
17342 Prev
.InImmediateEscalatingFunctionContext
;
17345 if (!MaybeODRUseExprs
.empty())
17346 std::swap(MaybeODRUseExprs
, ExprEvalContexts
.back().SavedMaybeODRUseExprs
);
17350 Sema::PushExpressionEvaluationContext(
17351 ExpressionEvaluationContext NewContext
, ReuseLambdaContextDecl_t
,
17352 ExpressionEvaluationContextRecord::ExpressionKind ExprContext
) {
17353 Decl
*ClosureContextDecl
= ExprEvalContexts
.back().ManglingContextDecl
;
17354 PushExpressionEvaluationContext(NewContext
, ClosureContextDecl
, ExprContext
);
17359 const DeclRefExpr
*CheckPossibleDeref(Sema
&S
, const Expr
*PossibleDeref
) {
17360 PossibleDeref
= PossibleDeref
->IgnoreParenImpCasts();
17361 if (const auto *E
= dyn_cast
<UnaryOperator
>(PossibleDeref
)) {
17362 if (E
->getOpcode() == UO_Deref
)
17363 return CheckPossibleDeref(S
, E
->getSubExpr());
17364 } else if (const auto *E
= dyn_cast
<ArraySubscriptExpr
>(PossibleDeref
)) {
17365 return CheckPossibleDeref(S
, E
->getBase());
17366 } else if (const auto *E
= dyn_cast
<MemberExpr
>(PossibleDeref
)) {
17367 return CheckPossibleDeref(S
, E
->getBase());
17368 } else if (const auto E
= dyn_cast
<DeclRefExpr
>(PossibleDeref
)) {
17370 QualType Ty
= E
->getType();
17371 if (const auto *Ptr
= Ty
->getAs
<PointerType
>())
17372 Inner
= Ptr
->getPointeeType();
17373 else if (const auto *Arr
= S
.Context
.getAsArrayType(Ty
))
17374 Inner
= Arr
->getElementType();
17378 if (Inner
->hasAttr(attr::NoDeref
))
17386 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord
&Rec
) {
17387 for (const Expr
*E
: Rec
.PossibleDerefs
) {
17388 const DeclRefExpr
*DeclRef
= CheckPossibleDeref(*this, E
);
17390 const ValueDecl
*Decl
= DeclRef
->getDecl();
17391 Diag(E
->getExprLoc(), diag::warn_dereference_of_noderef_type
)
17392 << Decl
->getName() << E
->getSourceRange();
17393 Diag(Decl
->getLocation(), diag::note_previous_decl
) << Decl
->getName();
17395 Diag(E
->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl
)
17396 << E
->getSourceRange();
17399 Rec
.PossibleDerefs
.clear();
17402 void Sema::CheckUnusedVolatileAssignment(Expr
*E
) {
17403 if (!E
->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20
)
17406 // Note: ignoring parens here is not justified by the standard rules, but
17407 // ignoring parentheses seems like a more reasonable approach, and this only
17408 // drives a deprecation warning so doesn't affect conformance.
17409 if (auto *BO
= dyn_cast
<BinaryOperator
>(E
->IgnoreParenImpCasts())) {
17410 if (BO
->getOpcode() == BO_Assign
) {
17411 auto &LHSs
= ExprEvalContexts
.back().VolatileAssignmentLHSs
;
17412 llvm::erase(LHSs
, BO
->getLHS());
17417 void Sema::MarkExpressionAsImmediateEscalating(Expr
*E
) {
17418 assert(getLangOpts().CPlusPlus20
&&
17419 ExprEvalContexts
.back().InImmediateEscalatingFunctionContext
&&
17420 "Cannot mark an immediate escalating expression outside of an "
17421 "immediate escalating context");
17422 if (auto *Call
= dyn_cast
<CallExpr
>(E
->IgnoreImplicit());
17423 Call
&& Call
->getCallee()) {
17424 if (auto *DeclRef
=
17425 dyn_cast
<DeclRefExpr
>(Call
->getCallee()->IgnoreImplicit()))
17426 DeclRef
->setIsImmediateEscalating(true);
17427 } else if (auto *Ctr
= dyn_cast
<CXXConstructExpr
>(E
->IgnoreImplicit())) {
17428 Ctr
->setIsImmediateEscalating(true);
17429 } else if (auto *DeclRef
= dyn_cast
<DeclRefExpr
>(E
->IgnoreImplicit())) {
17430 DeclRef
->setIsImmediateEscalating(true);
17432 assert(false && "expected an immediately escalating expression");
17434 if (FunctionScopeInfo
*FI
= getCurFunction())
17435 FI
->FoundImmediateEscalatingExpression
= true;
17438 ExprResult
Sema::CheckForImmediateInvocation(ExprResult E
, FunctionDecl
*Decl
) {
17439 if (isUnevaluatedContext() || !E
.isUsable() || !Decl
||
17440 !Decl
->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
17441 isCheckingDefaultArgumentOrInitializer() ||
17442 RebuildingImmediateInvocation
|| isImmediateFunctionContext())
17445 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17446 /// It's OK if this fails; we'll also remove this in
17447 /// HandleImmediateInvocations, but catching it here allows us to avoid
17448 /// walking the AST looking for it in simple cases.
17449 if (auto *Call
= dyn_cast
<CallExpr
>(E
.get()->IgnoreImplicit()))
17450 if (auto *DeclRef
=
17451 dyn_cast
<DeclRefExpr
>(Call
->getCallee()->IgnoreImplicit()))
17452 ExprEvalContexts
.back().ReferenceToConsteval
.erase(DeclRef
);
17454 // C++23 [expr.const]/p16
17455 // An expression or conversion is immediate-escalating if it is not initially
17456 // in an immediate function context and it is [...] an immediate invocation
17457 // that is not a constant expression and is not a subexpression of an
17458 // immediate invocation.
17460 auto CheckConstantExpressionAndKeepResult
= [&]() {
17461 llvm::SmallVector
<PartialDiagnosticAt
, 8> Notes
;
17462 Expr::EvalResult Eval
;
17463 Eval
.Diag
= &Notes
;
17464 bool Res
= E
.get()->EvaluateAsConstantExpr(
17465 Eval
, getASTContext(), ConstantExprKind::ImmediateInvocation
);
17466 if (Res
&& Notes
.empty()) {
17467 Cached
= std::move(Eval
.Val
);
17473 if (!E
.get()->isValueDependent() &&
17474 ExprEvalContexts
.back().InImmediateEscalatingFunctionContext
&&
17475 !CheckConstantExpressionAndKeepResult()) {
17476 MarkExpressionAsImmediateEscalating(E
.get());
17480 if (Cleanup
.exprNeedsCleanups()) {
17481 // Since an immediate invocation is a full expression itself - it requires
17482 // an additional ExprWithCleanups node, but it can participate to a bigger
17483 // full expression which actually requires cleanups to be run after so
17484 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
17485 // may discard cleanups for outer expression too early.
17487 // Note that ExprWithCleanups created here must always have empty cleanup
17489 // - compound literals do not create cleanup objects in C++ and immediate
17490 // invocations are C++-only.
17491 // - blocks are not allowed inside constant expressions and compiler will
17492 // issue an error if they appear there.
17494 // Hence, in correct code any cleanup objects created inside current
17495 // evaluation context must be outside the immediate invocation.
17496 E
= ExprWithCleanups::Create(getASTContext(), E
.get(),
17497 Cleanup
.cleanupsHaveSideEffects(), {});
17500 ConstantExpr
*Res
= ConstantExpr::Create(
17501 getASTContext(), E
.get(),
17502 ConstantExpr::getStorageKind(Decl
->getReturnType().getTypePtr(),
17504 /*IsImmediateInvocation*/ true);
17505 if (Cached
.hasValue())
17506 Res
->MoveIntoResult(Cached
, getASTContext());
17507 /// Value-dependent constant expressions should not be immediately
17508 /// evaluated until they are instantiated.
17509 if (!Res
->isValueDependent())
17510 ExprEvalContexts
.back().ImmediateInvocationCandidates
.emplace_back(Res
, 0);
17514 static void EvaluateAndDiagnoseImmediateInvocation(
17515 Sema
&SemaRef
, Sema::ImmediateInvocationCandidate Candidate
) {
17516 llvm::SmallVector
<PartialDiagnosticAt
, 8> Notes
;
17517 Expr::EvalResult Eval
;
17518 Eval
.Diag
= &Notes
;
17519 ConstantExpr
*CE
= Candidate
.getPointer();
17520 bool Result
= CE
->EvaluateAsConstantExpr(
17521 Eval
, SemaRef
.getASTContext(), ConstantExprKind::ImmediateInvocation
);
17522 if (!Result
|| !Notes
.empty()) {
17523 SemaRef
.FailedImmediateInvocations
.insert(CE
);
17524 Expr
*InnerExpr
= CE
->getSubExpr()->IgnoreImplicit();
17525 if (auto *FunctionalCast
= dyn_cast
<CXXFunctionalCastExpr
>(InnerExpr
))
17526 InnerExpr
= FunctionalCast
->getSubExpr()->IgnoreImplicit();
17527 FunctionDecl
*FD
= nullptr;
17528 if (auto *Call
= dyn_cast
<CallExpr
>(InnerExpr
))
17529 FD
= cast
<FunctionDecl
>(Call
->getCalleeDecl());
17530 else if (auto *Call
= dyn_cast
<CXXConstructExpr
>(InnerExpr
))
17531 FD
= Call
->getConstructor();
17532 else if (auto *Cast
= dyn_cast
<CastExpr
>(InnerExpr
))
17533 FD
= dyn_cast_or_null
<FunctionDecl
>(Cast
->getConversionFunction());
17535 assert(FD
&& FD
->isImmediateFunction() &&
17536 "could not find an immediate function in this expression");
17537 if (FD
->isInvalidDecl())
17539 SemaRef
.Diag(CE
->getBeginLoc(), diag::err_invalid_consteval_call
)
17540 << FD
<< FD
->isConsteval();
17542 SemaRef
.InnermostDeclarationWithDelayedImmediateInvocations()) {
17543 SemaRef
.Diag(Context
->Loc
, diag::note_invalid_consteval_initializer
)
17545 SemaRef
.Diag(Context
->Decl
->getBeginLoc(), diag::note_declared_at
);
17547 if (!FD
->isConsteval())
17548 SemaRef
.DiagnoseImmediateEscalatingReason(FD
);
17549 for (auto &Note
: Notes
)
17550 SemaRef
.Diag(Note
.first
, Note
.second
);
17553 CE
->MoveIntoResult(Eval
.Val
, SemaRef
.getASTContext());
17556 static void RemoveNestedImmediateInvocation(
17557 Sema
&SemaRef
, Sema::ExpressionEvaluationContextRecord
&Rec
,
17558 SmallVector
<Sema::ImmediateInvocationCandidate
, 4>::reverse_iterator It
) {
17559 struct ComplexRemove
: TreeTransform
<ComplexRemove
> {
17560 using Base
= TreeTransform
<ComplexRemove
>;
17561 llvm::SmallPtrSetImpl
<DeclRefExpr
*> &DRSet
;
17562 SmallVector
<Sema::ImmediateInvocationCandidate
, 4> &IISet
;
17563 SmallVector
<Sema::ImmediateInvocationCandidate
, 4>::reverse_iterator
17565 ComplexRemove(Sema
&SemaRef
, llvm::SmallPtrSetImpl
<DeclRefExpr
*> &DR
,
17566 SmallVector
<Sema::ImmediateInvocationCandidate
, 4> &II
,
17567 SmallVector
<Sema::ImmediateInvocationCandidate
,
17568 4>::reverse_iterator Current
)
17569 : Base(SemaRef
), DRSet(DR
), IISet(II
), CurrentII(Current
) {}
17570 void RemoveImmediateInvocation(ConstantExpr
* E
) {
17571 auto It
= std::find_if(CurrentII
, IISet
.rend(),
17572 [E
](Sema::ImmediateInvocationCandidate Elem
) {
17573 return Elem
.getPointer() == E
;
17575 // It is possible that some subexpression of the current immediate
17576 // invocation was handled from another expression evaluation context. Do
17577 // not handle the current immediate invocation if some of its
17578 // subexpressions failed before.
17579 if (It
== IISet
.rend()) {
17580 if (SemaRef
.FailedImmediateInvocations
.contains(E
))
17581 CurrentII
->setInt(1);
17583 It
->setInt(1); // Mark as deleted
17586 ExprResult
TransformConstantExpr(ConstantExpr
*E
) {
17587 if (!E
->isImmediateInvocation())
17588 return Base::TransformConstantExpr(E
);
17589 RemoveImmediateInvocation(E
);
17590 return Base::TransformExpr(E
->getSubExpr());
17592 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17593 /// we need to remove its DeclRefExpr from the DRSet.
17594 ExprResult
TransformCXXOperatorCallExpr(CXXOperatorCallExpr
*E
) {
17595 DRSet
.erase(cast
<DeclRefExpr
>(E
->getCallee()->IgnoreImplicit()));
17596 return Base::TransformCXXOperatorCallExpr(E
);
17598 /// Base::TransformUserDefinedLiteral doesn't preserve the
17599 /// UserDefinedLiteral node.
17600 ExprResult
TransformUserDefinedLiteral(UserDefinedLiteral
*E
) { return E
; }
17601 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
17603 ExprResult
TransformInitializer(Expr
*Init
, bool NotCopyInit
) {
17607 // We cannot use IgnoreImpCasts because we need to preserve
17608 // full expressions.
17610 if (auto *ICE
= dyn_cast
<ImplicitCastExpr
>(Init
))
17611 Init
= ICE
->getSubExpr();
17612 else if (auto *ICE
= dyn_cast
<MaterializeTemporaryExpr
>(Init
))
17613 Init
= ICE
->getSubExpr();
17617 /// ConstantExprs are the first layer of implicit node to be removed so if
17618 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
17619 if (auto *CE
= dyn_cast
<ConstantExpr
>(Init
);
17620 CE
&& CE
->isImmediateInvocation())
17621 RemoveImmediateInvocation(CE
);
17622 return Base::TransformInitializer(Init
, NotCopyInit
);
17624 ExprResult
TransformDeclRefExpr(DeclRefExpr
*E
) {
17628 ExprResult
TransformLambdaExpr(LambdaExpr
*E
) {
17629 // Do not rebuild lambdas to avoid creating a new type.
17630 // Lambdas have already been processed inside their eval contexts.
17633 bool AlwaysRebuild() { return false; }
17634 bool ReplacingOriginal() { return true; }
17635 bool AllowSkippingCXXConstructExpr() {
17636 bool Res
= AllowSkippingFirstCXXConstructExpr
;
17637 AllowSkippingFirstCXXConstructExpr
= true;
17640 bool AllowSkippingFirstCXXConstructExpr
= true;
17641 } Transformer(SemaRef
, Rec
.ReferenceToConsteval
,
17642 Rec
.ImmediateInvocationCandidates
, It
);
17644 /// CXXConstructExpr with a single argument are getting skipped by
17645 /// TreeTransform in some situtation because they could be implicit. This
17646 /// can only occur for the top-level CXXConstructExpr because it is used
17647 /// nowhere in the expression being transformed therefore will not be rebuilt.
17648 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
17649 /// skipping the first CXXConstructExpr.
17650 if (isa
<CXXConstructExpr
>(It
->getPointer()->IgnoreImplicit()))
17651 Transformer
.AllowSkippingFirstCXXConstructExpr
= false;
17653 ExprResult Res
= Transformer
.TransformExpr(It
->getPointer()->getSubExpr());
17654 // The result may not be usable in case of previous compilation errors.
17655 // In this case evaluation of the expression may result in crash so just
17656 // don't do anything further with the result.
17657 if (Res
.isUsable()) {
17658 Res
= SemaRef
.MaybeCreateExprWithCleanups(Res
);
17659 It
->getPointer()->setSubExpr(Res
.get());
17664 HandleImmediateInvocations(Sema
&SemaRef
,
17665 Sema::ExpressionEvaluationContextRecord
&Rec
) {
17666 if ((Rec
.ImmediateInvocationCandidates
.size() == 0 &&
17667 Rec
.ReferenceToConsteval
.size() == 0) ||
17668 Rec
.isImmediateFunctionContext() || SemaRef
.RebuildingImmediateInvocation
)
17671 /// When we have more than 1 ImmediateInvocationCandidates or previously
17672 /// failed immediate invocations, we need to check for nested
17673 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
17674 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
17676 if (Rec
.ImmediateInvocationCandidates
.size() > 1 ||
17677 !SemaRef
.FailedImmediateInvocations
.empty()) {
17679 /// Prevent sema calls during the tree transform from adding pointers that
17680 /// are already in the sets.
17681 llvm::SaveAndRestore
DisableIITracking(
17682 SemaRef
.RebuildingImmediateInvocation
, true);
17684 /// Prevent diagnostic during tree transfrom as they are duplicates
17685 Sema::TentativeAnalysisScope
DisableDiag(SemaRef
);
17687 for (auto It
= Rec
.ImmediateInvocationCandidates
.rbegin();
17688 It
!= Rec
.ImmediateInvocationCandidates
.rend(); It
++)
17690 RemoveNestedImmediateInvocation(SemaRef
, Rec
, It
);
17691 } else if (Rec
.ImmediateInvocationCandidates
.size() == 1 &&
17692 Rec
.ReferenceToConsteval
.size()) {
17693 struct SimpleRemove
: DynamicRecursiveASTVisitor
{
17694 llvm::SmallPtrSetImpl
<DeclRefExpr
*> &DRSet
;
17695 SimpleRemove(llvm::SmallPtrSetImpl
<DeclRefExpr
*> &S
) : DRSet(S
) {}
17696 bool VisitDeclRefExpr(DeclRefExpr
*E
) override
{
17698 return DRSet
.size();
17700 } Visitor(Rec
.ReferenceToConsteval
);
17701 Visitor
.TraverseStmt(
17702 Rec
.ImmediateInvocationCandidates
.front().getPointer()->getSubExpr());
17704 for (auto CE
: Rec
.ImmediateInvocationCandidates
)
17706 EvaluateAndDiagnoseImmediateInvocation(SemaRef
, CE
);
17707 for (auto *DR
: Rec
.ReferenceToConsteval
) {
17708 // If the expression is immediate escalating, it is not an error;
17709 // The outer context itself becomes immediate and further errors,
17710 // if any, will be handled by DiagnoseImmediateEscalatingReason.
17711 if (DR
->isImmediateEscalating())
17713 auto *FD
= cast
<FunctionDecl
>(DR
->getDecl());
17714 const NamedDecl
*ND
= FD
;
17715 if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(ND
);
17716 MD
&& (MD
->isLambdaStaticInvoker() || isLambdaCallOperator(MD
)))
17717 ND
= MD
->getParent();
17719 // C++23 [expr.const]/p16
17720 // An expression or conversion is immediate-escalating if it is not
17721 // initially in an immediate function context and it is [...] a
17722 // potentially-evaluated id-expression that denotes an immediate function
17723 // that is not a subexpression of an immediate invocation.
17724 bool ImmediateEscalating
= false;
17725 bool IsPotentiallyEvaluated
=
17727 Sema::ExpressionEvaluationContext::PotentiallyEvaluated
||
17729 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed
;
17730 if (SemaRef
.inTemplateInstantiation() && IsPotentiallyEvaluated
)
17731 ImmediateEscalating
= Rec
.InImmediateEscalatingFunctionContext
;
17733 if (!Rec
.InImmediateEscalatingFunctionContext
||
17734 (SemaRef
.inTemplateInstantiation() && !ImmediateEscalating
)) {
17735 SemaRef
.Diag(DR
->getBeginLoc(), diag::err_invalid_consteval_take_address
)
17736 << ND
<< isa
<CXXRecordDecl
>(ND
) << FD
->isConsteval();
17737 if (!FD
->getBuiltinID())
17738 SemaRef
.Diag(ND
->getLocation(), diag::note_declared_at
);
17740 SemaRef
.InnermostDeclarationWithDelayedImmediateInvocations()) {
17741 SemaRef
.Diag(Context
->Loc
, diag::note_invalid_consteval_initializer
)
17743 SemaRef
.Diag(Context
->Decl
->getBeginLoc(), diag::note_declared_at
);
17745 if (FD
->isImmediateEscalating() && !FD
->isConsteval())
17746 SemaRef
.DiagnoseImmediateEscalatingReason(FD
);
17749 SemaRef
.MarkExpressionAsImmediateEscalating(DR
);
17754 void Sema::PopExpressionEvaluationContext() {
17755 ExpressionEvaluationContextRecord
& Rec
= ExprEvalContexts
.back();
17756 unsigned NumTypos
= Rec
.NumTypos
;
17758 if (!Rec
.Lambdas
.empty()) {
17759 using ExpressionKind
= ExpressionEvaluationContextRecord::ExpressionKind
;
17760 if (!getLangOpts().CPlusPlus20
&&
17761 (Rec
.ExprContext
== ExpressionKind::EK_TemplateArgument
||
17762 Rec
.isUnevaluated() ||
17763 (Rec
.isConstantEvaluated() && !getLangOpts().CPlusPlus17
))) {
17765 if (Rec
.isUnevaluated()) {
17766 // C++11 [expr.prim.lambda]p2:
17767 // A lambda-expression shall not appear in an unevaluated operand
17769 D
= diag::err_lambda_unevaluated_operand
;
17770 } else if (Rec
.isConstantEvaluated() && !getLangOpts().CPlusPlus17
) {
17771 // C++1y [expr.const]p2:
17772 // A conditional-expression e is a core constant expression unless the
17773 // evaluation of e, following the rules of the abstract machine, would
17774 // evaluate [...] a lambda-expression.
17775 D
= diag::err_lambda_in_constant_expression
;
17776 } else if (Rec
.ExprContext
== ExpressionKind::EK_TemplateArgument
) {
17777 // C++17 [expr.prim.lamda]p2:
17778 // A lambda-expression shall not appear [...] in a template-argument.
17779 D
= diag::err_lambda_in_invalid_context
;
17781 llvm_unreachable("Couldn't infer lambda error message.");
17783 for (const auto *L
: Rec
.Lambdas
)
17784 Diag(L
->getBeginLoc(), D
);
17788 // Append the collected materialized temporaries into previous context before
17789 // exit if the previous also is a lifetime extending context.
17790 if (getLangOpts().CPlusPlus23
&& Rec
.InLifetimeExtendingContext
&&
17791 parentEvaluationContext().InLifetimeExtendingContext
&&
17792 !Rec
.ForRangeLifetimeExtendTemps
.empty()) {
17793 parentEvaluationContext().ForRangeLifetimeExtendTemps
.append(
17794 Rec
.ForRangeLifetimeExtendTemps
);
17797 WarnOnPendingNoDerefs(Rec
);
17798 HandleImmediateInvocations(*this, Rec
);
17800 // Warn on any volatile-qualified simple-assignments that are not discarded-
17801 // value expressions nor unevaluated operands (those cases get removed from
17802 // this list by CheckUnusedVolatileAssignment).
17803 for (auto *BO
: Rec
.VolatileAssignmentLHSs
)
17804 Diag(BO
->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile
)
17807 // When are coming out of an unevaluated context, clear out any
17808 // temporaries that we may have created as part of the evaluation of
17809 // the expression in that context: they aren't relevant because they
17810 // will never be constructed.
17811 if (Rec
.isUnevaluated() || Rec
.isConstantEvaluated()) {
17812 ExprCleanupObjects
.erase(ExprCleanupObjects
.begin() + Rec
.NumCleanupObjects
,
17813 ExprCleanupObjects
.end());
17814 Cleanup
= Rec
.ParentCleanup
;
17815 CleanupVarDeclMarking();
17816 std::swap(MaybeODRUseExprs
, Rec
.SavedMaybeODRUseExprs
);
17817 // Otherwise, merge the contexts together.
17819 Cleanup
.mergeFrom(Rec
.ParentCleanup
);
17820 MaybeODRUseExprs
.insert(Rec
.SavedMaybeODRUseExprs
.begin(),
17821 Rec
.SavedMaybeODRUseExprs
.end());
17824 // Pop the current expression evaluation context off the stack.
17825 ExprEvalContexts
.pop_back();
17827 // The global expression evaluation context record is never popped.
17828 ExprEvalContexts
.back().NumTypos
+= NumTypos
;
17831 void Sema::DiscardCleanupsInEvaluationContext() {
17832 ExprCleanupObjects
.erase(
17833 ExprCleanupObjects
.begin() + ExprEvalContexts
.back().NumCleanupObjects
,
17834 ExprCleanupObjects
.end());
17836 MaybeODRUseExprs
.clear();
17839 ExprResult
Sema::HandleExprEvaluationContextForTypeof(Expr
*E
) {
17840 ExprResult Result
= CheckPlaceholderExpr(E
);
17841 if (Result
.isInvalid())
17842 return ExprError();
17844 if (!E
->getType()->isVariablyModifiedType())
17846 return TransformToPotentiallyEvaluated(E
);
17849 /// Are we in a context that is potentially constant evaluated per C++20
17850 /// [expr.const]p12?
17851 static bool isPotentiallyConstantEvaluatedContext(Sema
&SemaRef
) {
17852 /// C++2a [expr.const]p12:
17853 // An expression or conversion is potentially constant evaluated if it is
17854 switch (SemaRef
.ExprEvalContexts
.back().Context
) {
17855 case Sema::ExpressionEvaluationContext::ConstantEvaluated
:
17856 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext
:
17858 // -- a manifestly constant-evaluated expression,
17859 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated
:
17860 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed
:
17861 case Sema::ExpressionEvaluationContext::DiscardedStatement
:
17862 // -- a potentially-evaluated expression,
17863 case Sema::ExpressionEvaluationContext::UnevaluatedList
:
17864 // -- an immediate subexpression of a braced-init-list,
17866 // -- [FIXME] an expression of the form & cast-expression that occurs
17867 // within a templated entity
17868 // -- a subexpression of one of the above that is not a subexpression of
17869 // a nested unevaluated operand.
17872 case Sema::ExpressionEvaluationContext::Unevaluated
:
17873 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract
:
17874 // Expressions in this context are never evaluated.
17877 llvm_unreachable("Invalid context");
17880 /// Return true if this function has a calling convention that requires mangling
17881 /// in the size of the parameter pack.
17882 static bool funcHasParameterSizeMangling(Sema
&S
, FunctionDecl
*FD
) {
17883 // These manglings don't do anything on non-Windows or non-x86 platforms, so
17884 // we don't need parameter type sizes.
17885 const llvm::Triple
&TT
= S
.Context
.getTargetInfo().getTriple();
17886 if (!TT
.isOSWindows() || !TT
.isX86())
17889 // If this is C++ and this isn't an extern "C" function, parameters do not
17890 // need to be complete. In this case, C++ mangling will apply, which doesn't
17891 // use the size of the parameters.
17892 if (S
.getLangOpts().CPlusPlus
&& !FD
->isExternC())
17895 // Stdcall, fastcall, and vectorcall need this special treatment.
17896 CallingConv CC
= FD
->getType()->castAs
<FunctionType
>()->getCallConv();
17898 case CC_X86StdCall
:
17899 case CC_X86FastCall
:
17900 case CC_X86VectorCall
:
17908 /// Require that all of the parameter types of function be complete. Normally,
17909 /// parameter types are only required to be complete when a function is called
17910 /// or defined, but to mangle functions with certain calling conventions, the
17911 /// mangler needs to know the size of the parameter list. In this situation,
17912 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
17913 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
17914 /// result in a linker error. Clang doesn't implement this behavior, and instead
17915 /// attempts to error at compile time.
17916 static void CheckCompleteParameterTypesForMangler(Sema
&S
, FunctionDecl
*FD
,
17917 SourceLocation Loc
) {
17918 class ParamIncompleteTypeDiagnoser
: public Sema::TypeDiagnoser
{
17920 ParmVarDecl
*Param
;
17923 ParamIncompleteTypeDiagnoser(FunctionDecl
*FD
, ParmVarDecl
*Param
)
17924 : FD(FD
), Param(Param
) {}
17926 void diagnose(Sema
&S
, SourceLocation Loc
, QualType T
) override
{
17927 CallingConv CC
= FD
->getType()->castAs
<FunctionType
>()->getCallConv();
17930 case CC_X86StdCall
:
17931 CCName
= "stdcall";
17933 case CC_X86FastCall
:
17934 CCName
= "fastcall";
17936 case CC_X86VectorCall
:
17937 CCName
= "vectorcall";
17940 llvm_unreachable("CC does not need mangling");
17943 S
.Diag(Loc
, diag::err_cconv_incomplete_param_type
)
17944 << Param
->getDeclName() << FD
->getDeclName() << CCName
;
17948 for (ParmVarDecl
*Param
: FD
->parameters()) {
17949 ParamIncompleteTypeDiagnoser
Diagnoser(FD
, Param
);
17950 S
.RequireCompleteType(Loc
, Param
->getType(), Diagnoser
);
17955 enum class OdrUseContext
{
17956 /// Declarations in this context are not odr-used.
17958 /// Declarations in this context are formally odr-used, but this is a
17959 /// dependent context.
17961 /// Declarations in this context are odr-used but not actually used (yet).
17963 /// Declarations in this context are used.
17968 /// Are we within a context in which references to resolved functions or to
17969 /// variables result in odr-use?
17970 static OdrUseContext
isOdrUseContext(Sema
&SemaRef
) {
17971 OdrUseContext Result
;
17973 switch (SemaRef
.ExprEvalContexts
.back().Context
) {
17974 case Sema::ExpressionEvaluationContext::Unevaluated
:
17975 case Sema::ExpressionEvaluationContext::UnevaluatedList
:
17976 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract
:
17977 return OdrUseContext::None
;
17979 case Sema::ExpressionEvaluationContext::ConstantEvaluated
:
17980 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext
:
17981 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated
:
17982 Result
= OdrUseContext::Used
;
17985 case Sema::ExpressionEvaluationContext::DiscardedStatement
:
17986 Result
= OdrUseContext::FormallyOdrUsed
;
17989 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed
:
17990 // A default argument formally results in odr-use, but doesn't actually
17991 // result in a use in any real sense until it itself is used.
17992 Result
= OdrUseContext::FormallyOdrUsed
;
17996 if (SemaRef
.CurContext
->isDependentContext())
17997 return OdrUseContext::Dependent
;
18002 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl
*Func
) {
18003 if (!Func
->isConstexpr())
18006 if (Func
->isImplicitlyInstantiable() || !Func
->isUserProvided())
18008 auto *CCD
= dyn_cast
<CXXConstructorDecl
>(Func
);
18009 return CCD
&& CCD
->getInheritedConstructor();
18012 void Sema::MarkFunctionReferenced(SourceLocation Loc
, FunctionDecl
*Func
,
18013 bool MightBeOdrUse
) {
18014 assert(Func
&& "No function?");
18016 Func
->setReferenced();
18018 // Recursive functions aren't really used until they're used from some other
18020 bool IsRecursiveCall
= CurContext
== Func
;
18022 // C++11 [basic.def.odr]p3:
18023 // A function whose name appears as a potentially-evaluated expression is
18024 // odr-used if it is the unique lookup result or the selected member of a
18025 // set of overloaded functions [...].
18027 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18028 // can just check that here.
18029 OdrUseContext OdrUse
=
18030 MightBeOdrUse
? isOdrUseContext(*this) : OdrUseContext::None
;
18031 if (IsRecursiveCall
&& OdrUse
== OdrUseContext::Used
)
18032 OdrUse
= OdrUseContext::FormallyOdrUsed
;
18034 // Trivial default constructors and destructors are never actually used.
18035 // FIXME: What about other special members?
18036 if (Func
->isTrivial() && !Func
->hasAttr
<DLLExportAttr
>() &&
18037 OdrUse
== OdrUseContext::Used
) {
18038 if (auto *Constructor
= dyn_cast
<CXXConstructorDecl
>(Func
))
18039 if (Constructor
->isDefaultConstructor())
18040 OdrUse
= OdrUseContext::FormallyOdrUsed
;
18041 if (isa
<CXXDestructorDecl
>(Func
))
18042 OdrUse
= OdrUseContext::FormallyOdrUsed
;
18045 // C++20 [expr.const]p12:
18046 // A function [...] is needed for constant evaluation if it is [...] a
18047 // constexpr function that is named by an expression that is potentially
18048 // constant evaluated
18049 bool NeededForConstantEvaluation
=
18050 isPotentiallyConstantEvaluatedContext(*this) &&
18051 isImplicitlyDefinableConstexprFunction(Func
);
18053 // Determine whether we require a function definition to exist, per
18054 // C++11 [temp.inst]p3:
18055 // Unless a function template specialization has been explicitly
18056 // instantiated or explicitly specialized, the function template
18057 // specialization is implicitly instantiated when the specialization is
18058 // referenced in a context that requires a function definition to exist.
18059 // C++20 [temp.inst]p7:
18060 // The existence of a definition of a [...] function is considered to
18061 // affect the semantics of the program if the [...] function is needed for
18062 // constant evaluation by an expression
18063 // C++20 [basic.def.odr]p10:
18064 // Every program shall contain exactly one definition of every non-inline
18065 // function or variable that is odr-used in that program outside of a
18066 // discarded statement
18067 // C++20 [special]p1:
18068 // The implementation will implicitly define [defaulted special members]
18069 // if they are odr-used or needed for constant evaluation.
18071 // Note that we skip the implicit instantiation of templates that are only
18072 // used in unused default arguments or by recursive calls to themselves.
18073 // This is formally non-conforming, but seems reasonable in practice.
18074 bool NeedDefinition
=
18075 !IsRecursiveCall
&&
18076 (OdrUse
== OdrUseContext::Used
||
18077 (NeededForConstantEvaluation
&& !Func
->isPureVirtual()));
18079 // C++14 [temp.expl.spec]p6:
18080 // If a template [...] is explicitly specialized then that specialization
18081 // shall be declared before the first use of that specialization that would
18082 // cause an implicit instantiation to take place, in every translation unit
18083 // in which such a use occurs
18084 if (NeedDefinition
&&
18085 (Func
->getTemplateSpecializationKind() != TSK_Undeclared
||
18086 Func
->getMemberSpecializationInfo()))
18087 checkSpecializationReachability(Loc
, Func
);
18089 if (getLangOpts().CUDA
)
18090 CUDA().CheckCall(Loc
, Func
);
18092 // If we need a definition, try to create one.
18093 if (NeedDefinition
&& !Func
->getBody()) {
18094 runWithSufficientStackSpace(Loc
, [&] {
18095 if (CXXConstructorDecl
*Constructor
=
18096 dyn_cast
<CXXConstructorDecl
>(Func
)) {
18097 Constructor
= cast
<CXXConstructorDecl
>(Constructor
->getFirstDecl());
18098 if (Constructor
->isDefaulted() && !Constructor
->isDeleted()) {
18099 if (Constructor
->isDefaultConstructor()) {
18100 if (Constructor
->isTrivial() &&
18101 !Constructor
->hasAttr
<DLLExportAttr
>())
18103 DefineImplicitDefaultConstructor(Loc
, Constructor
);
18104 } else if (Constructor
->isCopyConstructor()) {
18105 DefineImplicitCopyConstructor(Loc
, Constructor
);
18106 } else if (Constructor
->isMoveConstructor()) {
18107 DefineImplicitMoveConstructor(Loc
, Constructor
);
18109 } else if (Constructor
->getInheritedConstructor()) {
18110 DefineInheritingConstructor(Loc
, Constructor
);
18112 } else if (CXXDestructorDecl
*Destructor
=
18113 dyn_cast
<CXXDestructorDecl
>(Func
)) {
18114 Destructor
= cast
<CXXDestructorDecl
>(Destructor
->getFirstDecl());
18115 if (Destructor
->isDefaulted() && !Destructor
->isDeleted()) {
18116 if (Destructor
->isTrivial() && !Destructor
->hasAttr
<DLLExportAttr
>())
18118 DefineImplicitDestructor(Loc
, Destructor
);
18120 if (Destructor
->isVirtual() && getLangOpts().AppleKext
)
18121 MarkVTableUsed(Loc
, Destructor
->getParent());
18122 } else if (CXXMethodDecl
*MethodDecl
= dyn_cast
<CXXMethodDecl
>(Func
)) {
18123 if (MethodDecl
->isOverloadedOperator() &&
18124 MethodDecl
->getOverloadedOperator() == OO_Equal
) {
18125 MethodDecl
= cast
<CXXMethodDecl
>(MethodDecl
->getFirstDecl());
18126 if (MethodDecl
->isDefaulted() && !MethodDecl
->isDeleted()) {
18127 if (MethodDecl
->isCopyAssignmentOperator())
18128 DefineImplicitCopyAssignment(Loc
, MethodDecl
);
18129 else if (MethodDecl
->isMoveAssignmentOperator())
18130 DefineImplicitMoveAssignment(Loc
, MethodDecl
);
18132 } else if (isa
<CXXConversionDecl
>(MethodDecl
) &&
18133 MethodDecl
->getParent()->isLambda()) {
18134 CXXConversionDecl
*Conversion
=
18135 cast
<CXXConversionDecl
>(MethodDecl
->getFirstDecl());
18136 if (Conversion
->isLambdaToBlockPointerConversion())
18137 DefineImplicitLambdaToBlockPointerConversion(Loc
, Conversion
);
18139 DefineImplicitLambdaToFunctionPointerConversion(Loc
, Conversion
);
18140 } else if (MethodDecl
->isVirtual() && getLangOpts().AppleKext
)
18141 MarkVTableUsed(Loc
, MethodDecl
->getParent());
18144 if (Func
->isDefaulted() && !Func
->isDeleted()) {
18145 DefaultedComparisonKind DCK
= getDefaultedComparisonKind(Func
);
18146 if (DCK
!= DefaultedComparisonKind::None
)
18147 DefineDefaultedComparison(Loc
, Func
, DCK
);
18150 // Implicit instantiation of function templates and member functions of
18151 // class templates.
18152 if (Func
->isImplicitlyInstantiable()) {
18153 TemplateSpecializationKind TSK
=
18154 Func
->getTemplateSpecializationKindForInstantiation();
18155 SourceLocation PointOfInstantiation
= Func
->getPointOfInstantiation();
18156 bool FirstInstantiation
= PointOfInstantiation
.isInvalid();
18157 if (FirstInstantiation
) {
18158 PointOfInstantiation
= Loc
;
18159 if (auto *MSI
= Func
->getMemberSpecializationInfo())
18160 MSI
->setPointOfInstantiation(Loc
);
18161 // FIXME: Notify listener.
18163 Func
->setTemplateSpecializationKind(TSK
, PointOfInstantiation
);
18164 } else if (TSK
!= TSK_ImplicitInstantiation
) {
18165 // Use the point of use as the point of instantiation, instead of the
18166 // point of explicit instantiation (which we track as the actual point
18167 // of instantiation). This gives better backtraces in diagnostics.
18168 PointOfInstantiation
= Loc
;
18171 if (FirstInstantiation
|| TSK
!= TSK_ImplicitInstantiation
||
18172 Func
->isConstexpr()) {
18173 if (isa
<CXXRecordDecl
>(Func
->getDeclContext()) &&
18174 cast
<CXXRecordDecl
>(Func
->getDeclContext())->isLocalClass() &&
18175 CodeSynthesisContexts
.size())
18176 PendingLocalImplicitInstantiations
.push_back(
18177 std::make_pair(Func
, PointOfInstantiation
));
18178 else if (Func
->isConstexpr())
18179 // Do not defer instantiations of constexpr functions, to avoid the
18180 // expression evaluator needing to call back into Sema if it sees a
18181 // call to such a function.
18182 InstantiateFunctionDefinition(PointOfInstantiation
, Func
);
18184 Func
->setInstantiationIsPending(true);
18185 PendingInstantiations
.push_back(
18186 std::make_pair(Func
, PointOfInstantiation
));
18187 if (llvm::isTimeTraceVerbose()) {
18188 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
18190 llvm::raw_string_ostream
OS(Name
);
18191 Func
->getNameForDiagnostic(OS
, getPrintingPolicy(),
18192 /*Qualified=*/true);
18196 // Notify the consumer that a function was implicitly instantiated.
18197 Consumer
.HandleCXXImplicitFunctionInstantiation(Func
);
18201 // Walk redefinitions, as some of them may be instantiable.
18202 for (auto *i
: Func
->redecls()) {
18203 if (!i
->isUsed(false) && i
->isImplicitlyInstantiable())
18204 MarkFunctionReferenced(Loc
, i
, MightBeOdrUse
);
18210 // If a constructor was defined in the context of a default parameter
18211 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18212 // context), its initializers may not be referenced yet.
18213 if (CXXConstructorDecl
*Constructor
= dyn_cast
<CXXConstructorDecl
>(Func
)) {
18214 EnterExpressionEvaluationContext
EvalContext(
18216 Constructor
->isImmediateFunction()
18217 ? ExpressionEvaluationContext::ImmediateFunctionContext
18218 : ExpressionEvaluationContext::PotentiallyEvaluated
,
18220 for (CXXCtorInitializer
*Init
: Constructor
->inits()) {
18221 if (Init
->isInClassMemberInitializer())
18222 runWithSufficientStackSpace(Init
->getSourceLocation(), [&]() {
18223 MarkDeclarationsReferencedInExpr(Init
->getInit());
18228 // C++14 [except.spec]p17:
18229 // An exception-specification is considered to be needed when:
18230 // - the function is odr-used or, if it appears in an unevaluated operand,
18231 // would be odr-used if the expression were potentially-evaluated;
18233 // Note, we do this even if MightBeOdrUse is false. That indicates that the
18234 // function is a pure virtual function we're calling, and in that case the
18235 // function was selected by overload resolution and we need to resolve its
18236 // exception specification for a different reason.
18237 const FunctionProtoType
*FPT
= Func
->getType()->getAs
<FunctionProtoType
>();
18238 if (FPT
&& isUnresolvedExceptionSpec(FPT
->getExceptionSpecType()))
18239 ResolveExceptionSpec(Loc
, FPT
);
18241 // A callee could be called by a host function then by a device function.
18242 // If we only try recording once, we will miss recording the use on device
18243 // side. Therefore keep trying until it is recorded.
18244 if (LangOpts
.OffloadImplicitHostDeviceTemplates
&& LangOpts
.CUDAIsDevice
&&
18245 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice
.count(Func
))
18246 CUDA().RecordImplicitHostDeviceFuncUsedByDevice(Func
);
18248 // If this is the first "real" use, act on that.
18249 if (OdrUse
== OdrUseContext::Used
&& !Func
->isUsed(/*CheckUsedAttr=*/false)) {
18250 // Keep track of used but undefined functions.
18251 if (!Func
->isDefined()) {
18252 if (mightHaveNonExternalLinkage(Func
))
18253 UndefinedButUsed
.insert(std::make_pair(Func
->getCanonicalDecl(), Loc
));
18254 else if (Func
->getMostRecentDecl()->isInlined() &&
18255 !LangOpts
.GNUInline
&&
18256 !Func
->getMostRecentDecl()->hasAttr
<GNUInlineAttr
>())
18257 UndefinedButUsed
.insert(std::make_pair(Func
->getCanonicalDecl(), Loc
));
18258 else if (isExternalWithNoLinkageType(Func
))
18259 UndefinedButUsed
.insert(std::make_pair(Func
->getCanonicalDecl(), Loc
));
18262 // Some x86 Windows calling conventions mangle the size of the parameter
18263 // pack into the name. Computing the size of the parameters requires the
18264 // parameter types to be complete. Check that now.
18265 if (funcHasParameterSizeMangling(*this, Func
))
18266 CheckCompleteParameterTypesForMangler(*this, Func
, Loc
);
18268 // In the MS C++ ABI, the compiler emits destructor variants where they are
18269 // used. If the destructor is used here but defined elsewhere, mark the
18270 // virtual base destructors referenced. If those virtual base destructors
18271 // are inline, this will ensure they are defined when emitting the complete
18272 // destructor variant. This checking may be redundant if the destructor is
18273 // provided later in this TU.
18274 if (Context
.getTargetInfo().getCXXABI().isMicrosoft()) {
18275 if (auto *Dtor
= dyn_cast
<CXXDestructorDecl
>(Func
)) {
18276 CXXRecordDecl
*Parent
= Dtor
->getParent();
18277 if (Parent
->getNumVBases() > 0 && !Dtor
->getBody())
18278 CheckCompleteDestructorVariant(Loc
, Dtor
);
18282 Func
->markUsed(Context
);
18286 /// Directly mark a variable odr-used. Given a choice, prefer to use
18287 /// MarkVariableReferenced since it does additional checks and then
18288 /// calls MarkVarDeclODRUsed.
18289 /// If the variable must be captured:
18290 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18291 /// - else capture it in the DeclContext that maps to the
18292 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18294 MarkVarDeclODRUsed(ValueDecl
*V
, SourceLocation Loc
, Sema
&SemaRef
,
18295 const unsigned *const FunctionScopeIndexToStopAt
= nullptr) {
18296 // Keep track of used but undefined variables.
18297 // FIXME: We shouldn't suppress this warning for static data members.
18298 VarDecl
*Var
= V
->getPotentiallyDecomposedVarDecl();
18299 assert(Var
&& "expected a capturable variable");
18301 if (Var
->hasDefinition(SemaRef
.Context
) == VarDecl::DeclarationOnly
&&
18302 (!Var
->isExternallyVisible() || Var
->isInline() ||
18303 SemaRef
.isExternalWithNoLinkageType(Var
)) &&
18304 !(Var
->isStaticDataMember() && Var
->hasInit())) {
18305 SourceLocation
&old
= SemaRef
.UndefinedButUsed
[Var
->getCanonicalDecl()];
18306 if (old
.isInvalid())
18309 QualType CaptureType
, DeclRefType
;
18310 if (SemaRef
.LangOpts
.OpenMP
)
18311 SemaRef
.OpenMP().tryCaptureOpenMPLambdas(V
);
18312 SemaRef
.tryCaptureVariable(V
, Loc
, Sema::TryCapture_Implicit
,
18313 /*EllipsisLoc*/ SourceLocation(),
18314 /*BuildAndDiagnose*/ true, CaptureType
,
18315 DeclRefType
, FunctionScopeIndexToStopAt
);
18317 if (SemaRef
.LangOpts
.CUDA
&& Var
->hasGlobalStorage()) {
18318 auto *FD
= dyn_cast_or_null
<FunctionDecl
>(SemaRef
.CurContext
);
18319 auto VarTarget
= SemaRef
.CUDA().IdentifyTarget(Var
);
18320 auto UserTarget
= SemaRef
.CUDA().IdentifyTarget(FD
);
18321 if (VarTarget
== SemaCUDA::CVT_Host
&&
18322 (UserTarget
== CUDAFunctionTarget::Device
||
18323 UserTarget
== CUDAFunctionTarget::HostDevice
||
18324 UserTarget
== CUDAFunctionTarget::Global
)) {
18325 // Diagnose ODR-use of host global variables in device functions.
18326 // Reference of device global variables in host functions is allowed
18327 // through shadow variables therefore it is not diagnosed.
18328 if (SemaRef
.LangOpts
.CUDAIsDevice
&& !SemaRef
.LangOpts
.HIPStdPar
) {
18329 SemaRef
.targetDiag(Loc
, diag::err_ref_bad_target
)
18330 << /*host*/ 2 << /*variable*/ 1 << Var
18331 << llvm::to_underlying(UserTarget
);
18332 SemaRef
.targetDiag(Var
->getLocation(),
18333 Var
->getType().isConstQualified()
18334 ? diag::note_cuda_const_var_unpromoted
18335 : diag::note_cuda_host_var
);
18337 } else if (VarTarget
== SemaCUDA::CVT_Device
&&
18338 !Var
->hasAttr
<CUDASharedAttr
>() &&
18339 (UserTarget
== CUDAFunctionTarget::Host
||
18340 UserTarget
== CUDAFunctionTarget::HostDevice
)) {
18341 // Record a CUDA/HIP device side variable if it is ODR-used
18342 // by host code. This is done conservatively, when the variable is
18343 // referenced in any of the following contexts:
18344 // - a non-function context
18345 // - a host function
18346 // - a host device function
18347 // This makes the ODR-use of the device side variable by host code to
18348 // be visible in the device compilation for the compiler to be able to
18349 // emit template variables instantiated by host code only and to
18350 // externalize the static device side variable ODR-used by host code.
18351 if (!Var
->hasExternalStorage())
18352 SemaRef
.getASTContext().CUDADeviceVarODRUsedByHost
.insert(Var
);
18353 else if (SemaRef
.LangOpts
.GPURelocatableDeviceCode
&&
18354 (!FD
|| (!FD
->getDescribedFunctionTemplate() &&
18355 SemaRef
.getASTContext().GetGVALinkageForFunction(FD
) ==
18356 GVA_StrongExternal
)))
18357 SemaRef
.getASTContext().CUDAExternalDeviceDeclODRUsedByHost
.insert(Var
);
18361 V
->markUsed(SemaRef
.Context
);
18364 void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl
*Capture
,
18365 SourceLocation Loc
,
18366 unsigned CapturingScopeIndex
) {
18367 MarkVarDeclODRUsed(Capture
, Loc
, *this, &CapturingScopeIndex
);
18370 void diagnoseUncapturableValueReferenceOrBinding(Sema
&S
, SourceLocation loc
,
18372 DeclContext
*VarDC
= var
->getDeclContext();
18374 // If the parameter still belongs to the translation unit, then
18375 // we're actually just using one parameter in the declaration of
18377 if (isa
<ParmVarDecl
>(var
) &&
18378 isa
<TranslationUnitDecl
>(VarDC
))
18381 // For C code, don't diagnose about capture if we're not actually in code
18382 // right now; it's impossible to write a non-constant expression outside of
18383 // function context, so we'll get other (more useful) diagnostics later.
18385 // For C++, things get a bit more nasty... it would be nice to suppress this
18386 // diagnostic for certain cases like using a local variable in an array bound
18387 // for a member of a local class, but the correct predicate is not obvious.
18388 if (!S
.getLangOpts().CPlusPlus
&& !S
.CurContext
->isFunctionOrMethod())
18391 unsigned ValueKind
= isa
<BindingDecl
>(var
) ? 1 : 0;
18392 unsigned ContextKind
= 3; // unknown
18393 if (isa
<CXXMethodDecl
>(VarDC
) &&
18394 cast
<CXXRecordDecl
>(VarDC
->getParent())->isLambda()) {
18396 } else if (isa
<FunctionDecl
>(VarDC
)) {
18398 } else if (isa
<BlockDecl
>(VarDC
)) {
18402 S
.Diag(loc
, diag::err_reference_to_local_in_enclosing_context
)
18403 << var
<< ValueKind
<< ContextKind
<< VarDC
;
18404 S
.Diag(var
->getLocation(), diag::note_entity_declared_at
)
18407 // FIXME: Add additional diagnostic info about class etc. which prevents
18411 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo
*CSI
,
18413 bool &SubCapturesAreNested
,
18414 QualType
&CaptureType
,
18415 QualType
&DeclRefType
) {
18416 // Check whether we've already captured it.
18417 if (CSI
->CaptureMap
.count(Var
)) {
18418 // If we found a capture, any subcaptures are nested.
18419 SubCapturesAreNested
= true;
18421 // Retrieve the capture type for this variable.
18422 CaptureType
= CSI
->getCapture(Var
).getCaptureType();
18424 // Compute the type of an expression that refers to this variable.
18425 DeclRefType
= CaptureType
.getNonReferenceType();
18427 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18428 // are mutable in the sense that user can change their value - they are
18429 // private instances of the captured declarations.
18430 const Capture
&Cap
= CSI
->getCapture(Var
);
18431 if (Cap
.isCopyCapture() &&
18432 !(isa
<LambdaScopeInfo
>(CSI
) &&
18433 !cast
<LambdaScopeInfo
>(CSI
)->lambdaCaptureShouldBeConst()) &&
18434 !(isa
<CapturedRegionScopeInfo
>(CSI
) &&
18435 cast
<CapturedRegionScopeInfo
>(CSI
)->CapRegionKind
== CR_OpenMP
))
18436 DeclRefType
.addConst();
18442 // Only block literals, captured statements, and lambda expressions can
18443 // capture; other scopes don't work.
18444 static DeclContext
*getParentOfCapturingContextOrNull(DeclContext
*DC
,
18446 SourceLocation Loc
,
18447 const bool Diagnose
,
18449 if (isa
<BlockDecl
>(DC
) || isa
<CapturedDecl
>(DC
) || isLambdaCallOperator(DC
))
18450 return getLambdaAwareParentOfDeclContext(DC
);
18452 VarDecl
*Underlying
= Var
->getPotentiallyDecomposedVarDecl();
18454 if (Underlying
->hasLocalStorage() && Diagnose
)
18455 diagnoseUncapturableValueReferenceOrBinding(S
, Loc
, Var
);
18460 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18461 // certain types of variables (unnamed, variably modified types etc.)
18462 // so check for eligibility.
18463 static bool isVariableCapturable(CapturingScopeInfo
*CSI
, ValueDecl
*Var
,
18464 SourceLocation Loc
, const bool Diagnose
,
18467 assert((isa
<VarDecl
, BindingDecl
>(Var
)) &&
18468 "Only variables and structured bindings can be captured");
18470 bool IsBlock
= isa
<BlockScopeInfo
>(CSI
);
18471 bool IsLambda
= isa
<LambdaScopeInfo
>(CSI
);
18473 // Lambdas are not allowed to capture unnamed variables
18474 // (e.g. anonymous unions).
18475 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18476 // assuming that's the intent.
18477 if (IsLambda
&& !Var
->getDeclName()) {
18479 S
.Diag(Loc
, diag::err_lambda_capture_anonymous_var
);
18480 S
.Diag(Var
->getLocation(), diag::note_declared_at
);
18485 // Prohibit variably-modified types in blocks; they're difficult to deal with.
18486 if (Var
->getType()->isVariablyModifiedType() && IsBlock
) {
18488 S
.Diag(Loc
, diag::err_ref_vm_type
);
18489 S
.Diag(Var
->getLocation(), diag::note_previous_decl
) << Var
;
18493 // Prohibit structs with flexible array members too.
18494 // We cannot capture what is in the tail end of the struct.
18495 if (const RecordType
*VTTy
= Var
->getType()->getAs
<RecordType
>()) {
18496 if (VTTy
->getDecl()->hasFlexibleArrayMember()) {
18499 S
.Diag(Loc
, diag::err_ref_flexarray_type
);
18501 S
.Diag(Loc
, diag::err_lambda_capture_flexarray_type
) << Var
;
18502 S
.Diag(Var
->getLocation(), diag::note_previous_decl
) << Var
;
18507 const bool HasBlocksAttr
= Var
->hasAttr
<BlocksAttr
>();
18508 // Lambdas and captured statements are not allowed to capture __block
18509 // variables; they don't support the expected semantics.
18510 if (HasBlocksAttr
&& (IsLambda
|| isa
<CapturedRegionScopeInfo
>(CSI
))) {
18512 S
.Diag(Loc
, diag::err_capture_block_variable
) << Var
<< !IsLambda
;
18513 S
.Diag(Var
->getLocation(), diag::note_previous_decl
) << Var
;
18517 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18518 if (S
.getLangOpts().OpenCL
&& IsBlock
&&
18519 Var
->getType()->isBlockPointerType()) {
18521 S
.Diag(Loc
, diag::err_opencl_block_ref_block
);
18525 if (isa
<BindingDecl
>(Var
)) {
18526 if (!IsLambda
|| !S
.getLangOpts().CPlusPlus
) {
18528 diagnoseUncapturableValueReferenceOrBinding(S
, Loc
, Var
);
18530 } else if (Diagnose
&& S
.getLangOpts().CPlusPlus
) {
18531 S
.Diag(Loc
, S
.LangOpts
.CPlusPlus20
18532 ? diag::warn_cxx17_compat_capture_binding
18533 : diag::ext_capture_binding
)
18535 S
.Diag(Var
->getLocation(), diag::note_entity_declared_at
) << Var
;
18542 // Returns true if the capture by block was successful.
18543 static bool captureInBlock(BlockScopeInfo
*BSI
, ValueDecl
*Var
,
18544 SourceLocation Loc
, const bool BuildAndDiagnose
,
18545 QualType
&CaptureType
, QualType
&DeclRefType
,
18546 const bool Nested
, Sema
&S
, bool Invalid
) {
18547 bool ByRef
= false;
18549 // Blocks are not allowed to capture arrays, excepting OpenCL.
18550 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18551 // (decayed to pointers).
18552 if (!Invalid
&& !S
.getLangOpts().OpenCL
&& CaptureType
->isArrayType()) {
18553 if (BuildAndDiagnose
) {
18554 S
.Diag(Loc
, diag::err_ref_array_type
);
18555 S
.Diag(Var
->getLocation(), diag::note_previous_decl
) << Var
;
18562 // Forbid the block-capture of autoreleasing variables.
18564 CaptureType
.getObjCLifetime() == Qualifiers::OCL_Autoreleasing
) {
18565 if (BuildAndDiagnose
) {
18566 S
.Diag(Loc
, diag::err_arc_autoreleasing_capture
)
18568 S
.Diag(Var
->getLocation(), diag::note_previous_decl
) << Var
;
18575 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18576 if (const auto *PT
= CaptureType
->getAs
<PointerType
>()) {
18577 QualType PointeeTy
= PT
->getPointeeType();
18579 if (!Invalid
&& PointeeTy
->getAs
<ObjCObjectPointerType
>() &&
18580 PointeeTy
.getObjCLifetime() == Qualifiers::OCL_Autoreleasing
&&
18581 !S
.Context
.hasDirectOwnershipQualifier(PointeeTy
)) {
18582 if (BuildAndDiagnose
) {
18583 SourceLocation VarLoc
= Var
->getLocation();
18584 S
.Diag(Loc
, diag::warn_block_capture_autoreleasing
);
18585 S
.Diag(VarLoc
, diag::note_declare_parameter_strong
);
18590 const bool HasBlocksAttr
= Var
->hasAttr
<BlocksAttr
>();
18591 if (HasBlocksAttr
|| CaptureType
->isReferenceType() ||
18592 (S
.getLangOpts().OpenMP
&& S
.OpenMP().isOpenMPCapturedDecl(Var
))) {
18593 // Block capture by reference does not change the capture or
18594 // declaration reference types.
18597 // Block capture by copy introduces 'const'.
18598 CaptureType
= CaptureType
.getNonReferenceType().withConst();
18599 DeclRefType
= CaptureType
;
18602 // Actually capture the variable.
18603 if (BuildAndDiagnose
)
18604 BSI
->addCapture(Var
, HasBlocksAttr
, ByRef
, Nested
, Loc
, SourceLocation(),
18605 CaptureType
, Invalid
);
18610 /// Capture the given variable in the captured region.
18611 static bool captureInCapturedRegion(
18612 CapturedRegionScopeInfo
*RSI
, ValueDecl
*Var
, SourceLocation Loc
,
18613 const bool BuildAndDiagnose
, QualType
&CaptureType
, QualType
&DeclRefType
,
18614 const bool RefersToCapturedVariable
, Sema::TryCaptureKind Kind
,
18615 bool IsTopScope
, Sema
&S
, bool Invalid
) {
18616 // By default, capture variables by reference.
18618 if (IsTopScope
&& Kind
!= Sema::TryCapture_Implicit
) {
18619 ByRef
= (Kind
== Sema::TryCapture_ExplicitByRef
);
18620 } else if (S
.getLangOpts().OpenMP
&& RSI
->CapRegionKind
== CR_OpenMP
) {
18621 // Using an LValue reference type is consistent with Lambdas (see below).
18622 if (S
.OpenMP().isOpenMPCapturedDecl(Var
)) {
18623 bool HasConst
= DeclRefType
.isConstQualified();
18624 DeclRefType
= DeclRefType
.getUnqualifiedType();
18625 // Don't lose diagnostics about assignments to const.
18627 DeclRefType
.addConst();
18629 // Do not capture firstprivates in tasks.
18630 if (S
.OpenMP().isOpenMPPrivateDecl(Var
, RSI
->OpenMPLevel
,
18631 RSI
->OpenMPCaptureLevel
) != OMPC_unknown
)
18633 ByRef
= S
.OpenMP().isOpenMPCapturedByRef(Var
, RSI
->OpenMPLevel
,
18634 RSI
->OpenMPCaptureLevel
);
18638 CaptureType
= S
.Context
.getLValueReferenceType(DeclRefType
);
18640 CaptureType
= DeclRefType
;
18642 // Actually capture the variable.
18643 if (BuildAndDiagnose
)
18644 RSI
->addCapture(Var
, /*isBlock*/ false, ByRef
, RefersToCapturedVariable
,
18645 Loc
, SourceLocation(), CaptureType
, Invalid
);
18650 /// Capture the given variable in the lambda.
18651 static bool captureInLambda(LambdaScopeInfo
*LSI
, ValueDecl
*Var
,
18652 SourceLocation Loc
, const bool BuildAndDiagnose
,
18653 QualType
&CaptureType
, QualType
&DeclRefType
,
18654 const bool RefersToCapturedVariable
,
18655 const Sema::TryCaptureKind Kind
,
18656 SourceLocation EllipsisLoc
, const bool IsTopScope
,
18657 Sema
&S
, bool Invalid
) {
18658 // Determine whether we are capturing by reference or by value.
18659 bool ByRef
= false;
18660 if (IsTopScope
&& Kind
!= Sema::TryCapture_Implicit
) {
18661 ByRef
= (Kind
== Sema::TryCapture_ExplicitByRef
);
18663 ByRef
= (LSI
->ImpCaptureStyle
== LambdaScopeInfo::ImpCap_LambdaByref
);
18666 if (BuildAndDiagnose
&& S
.Context
.getTargetInfo().getTriple().isWasm() &&
18667 CaptureType
.getNonReferenceType().isWebAssemblyReferenceType()) {
18668 S
.Diag(Loc
, diag::err_wasm_ca_reference
) << 0;
18672 // Compute the type of the field that will capture this variable.
18674 // C++11 [expr.prim.lambda]p15:
18675 // An entity is captured by reference if it is implicitly or
18676 // explicitly captured but not captured by copy. It is
18677 // unspecified whether additional unnamed non-static data
18678 // members are declared in the closure type for entities
18679 // captured by reference.
18681 // FIXME: It is not clear whether we want to build an lvalue reference
18682 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
18683 // to do the former, while EDG does the latter. Core issue 1249 will
18684 // clarify, but for now we follow GCC because it's a more permissive and
18685 // easily defensible position.
18686 CaptureType
= S
.Context
.getLValueReferenceType(DeclRefType
);
18688 // C++11 [expr.prim.lambda]p14:
18689 // For each entity captured by copy, an unnamed non-static
18690 // data member is declared in the closure type. The
18691 // declaration order of these members is unspecified. The type
18692 // of such a data member is the type of the corresponding
18693 // captured entity if the entity is not a reference to an
18694 // object, or the referenced type otherwise. [Note: If the
18695 // captured entity is a reference to a function, the
18696 // corresponding data member is also a reference to a
18697 // function. - end note ]
18698 if (const ReferenceType
*RefType
= CaptureType
->getAs
<ReferenceType
>()){
18699 if (!RefType
->getPointeeType()->isFunctionType())
18700 CaptureType
= RefType
->getPointeeType();
18703 // Forbid the lambda copy-capture of autoreleasing variables.
18705 CaptureType
.getObjCLifetime() == Qualifiers::OCL_Autoreleasing
) {
18706 if (BuildAndDiagnose
) {
18707 S
.Diag(Loc
, diag::err_arc_autoreleasing_capture
) << /*lambda*/ 1;
18708 S
.Diag(Var
->getLocation(), diag::note_previous_decl
)
18709 << Var
->getDeclName();
18716 // Make sure that by-copy captures are of a complete and non-abstract type.
18717 if (!Invalid
&& BuildAndDiagnose
) {
18718 if (!CaptureType
->isDependentType() &&
18719 S
.RequireCompleteSizedType(
18721 diag::err_capture_of_incomplete_or_sizeless_type
,
18722 Var
->getDeclName()))
18724 else if (S
.RequireNonAbstractType(Loc
, CaptureType
,
18725 diag::err_capture_of_abstract_type
))
18730 // Compute the type of a reference to this captured variable.
18732 DeclRefType
= CaptureType
.getNonReferenceType();
18734 // C++ [expr.prim.lambda]p5:
18735 // The closure type for a lambda-expression has a public inline
18736 // function call operator [...]. This function call operator is
18737 // declared const (9.3.1) if and only if the lambda-expression's
18738 // parameter-declaration-clause is not followed by mutable.
18739 DeclRefType
= CaptureType
.getNonReferenceType();
18740 bool Const
= LSI
->lambdaCaptureShouldBeConst();
18741 if (Const
&& !CaptureType
->isReferenceType())
18742 DeclRefType
.addConst();
18745 // Add the capture.
18746 if (BuildAndDiagnose
)
18747 LSI
->addCapture(Var
, /*isBlock=*/false, ByRef
, RefersToCapturedVariable
,
18748 Loc
, EllipsisLoc
, CaptureType
, Invalid
);
18753 static bool canCaptureVariableByCopy(ValueDecl
*Var
,
18754 const ASTContext
&Context
) {
18755 // Offer a Copy fix even if the type is dependent.
18756 if (Var
->getType()->isDependentType())
18758 QualType T
= Var
->getType().getNonReferenceType();
18759 if (T
.isTriviallyCopyableType(Context
))
18761 if (CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl()) {
18763 if (!(RD
= RD
->getDefinition()))
18765 if (RD
->hasSimpleCopyConstructor())
18767 if (RD
->hasUserDeclaredCopyConstructor())
18768 for (CXXConstructorDecl
*Ctor
: RD
->ctors())
18769 if (Ctor
->isCopyConstructor())
18770 return !Ctor
->isDeleted();
18775 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or
18776 /// default capture. Fixes may be omitted if they aren't allowed by the
18777 /// standard, for example we can't emit a default copy capture fix-it if we
18778 /// already explicitly copy capture capture another variable.
18779 static void buildLambdaCaptureFixit(Sema
&Sema
, LambdaScopeInfo
*LSI
,
18781 assert(LSI
->ImpCaptureStyle
== CapturingScopeInfo::ImpCap_None
);
18782 // Don't offer Capture by copy of default capture by copy fixes if Var is
18783 // known not to be copy constructible.
18784 bool ShouldOfferCopyFix
= canCaptureVariableByCopy(Var
, Sema
.getASTContext());
18786 SmallString
<32> FixBuffer
;
18787 StringRef Separator
= LSI
->NumExplicitCaptures
> 0 ? ", " : "";
18788 if (Var
->getDeclName().isIdentifier() && !Var
->getName().empty()) {
18789 SourceLocation VarInsertLoc
= LSI
->IntroducerRange
.getEnd();
18790 if (ShouldOfferCopyFix
) {
18791 // Offer fixes to insert an explicit capture for the variable.
18793 // [OtherCapture] -> [OtherCapture, VarName]
18794 FixBuffer
.assign({Separator
, Var
->getName()});
18795 Sema
.Diag(VarInsertLoc
, diag::note_lambda_variable_capture_fixit
)
18796 << Var
<< /*value*/ 0
18797 << FixItHint::CreateInsertion(VarInsertLoc
, FixBuffer
);
18799 // As above but capture by reference.
18800 FixBuffer
.assign({Separator
, "&", Var
->getName()});
18801 Sema
.Diag(VarInsertLoc
, diag::note_lambda_variable_capture_fixit
)
18802 << Var
<< /*reference*/ 1
18803 << FixItHint::CreateInsertion(VarInsertLoc
, FixBuffer
);
18806 // Only try to offer default capture if there are no captures excluding this
18807 // and init captures.
18810 // [&A, &B]: Don't offer.
18811 // [A, B]: Don't offer.
18812 if (llvm::any_of(LSI
->Captures
, [](Capture
&C
) {
18813 return !C
.isThisCapture() && !C
.isInitCapture();
18817 // The default capture specifiers, '=' or '&', must appear first in the
18819 SourceLocation DefaultInsertLoc
=
18820 LSI
->IntroducerRange
.getBegin().getLocWithOffset(1);
18822 if (ShouldOfferCopyFix
) {
18823 bool CanDefaultCopyCapture
= true;
18824 // [=, *this] OK since c++17
18825 // [=, this] OK since c++20
18826 if (LSI
->isCXXThisCaptured() && !Sema
.getLangOpts().CPlusPlus20
)
18827 CanDefaultCopyCapture
= Sema
.getLangOpts().CPlusPlus17
18828 ? LSI
->getCXXThisCapture().isCopyCapture()
18830 // We can't use default capture by copy if any captures already specified
18831 // capture by copy.
18832 if (CanDefaultCopyCapture
&& llvm::none_of(LSI
->Captures
, [](Capture
&C
) {
18833 return !C
.isThisCapture() && !C
.isInitCapture() && C
.isCopyCapture();
18835 FixBuffer
.assign({"=", Separator
});
18836 Sema
.Diag(DefaultInsertLoc
, diag::note_lambda_default_capture_fixit
)
18838 << FixItHint::CreateInsertion(DefaultInsertLoc
, FixBuffer
);
18842 // We can't use default capture by reference if any captures already specified
18843 // capture by reference.
18844 if (llvm::none_of(LSI
->Captures
, [](Capture
&C
) {
18845 return !C
.isInitCapture() && C
.isReferenceCapture() &&
18846 !C
.isThisCapture();
18848 FixBuffer
.assign({"&", Separator
});
18849 Sema
.Diag(DefaultInsertLoc
, diag::note_lambda_default_capture_fixit
)
18851 << FixItHint::CreateInsertion(DefaultInsertLoc
, FixBuffer
);
18855 bool Sema::tryCaptureVariable(
18856 ValueDecl
*Var
, SourceLocation ExprLoc
, TryCaptureKind Kind
,
18857 SourceLocation EllipsisLoc
, bool BuildAndDiagnose
, QualType
&CaptureType
,
18858 QualType
&DeclRefType
, const unsigned *const FunctionScopeIndexToStopAt
) {
18859 // An init-capture is notionally from the context surrounding its
18860 // declaration, but its parent DC is the lambda class.
18861 DeclContext
*VarDC
= Var
->getDeclContext();
18862 DeclContext
*DC
= CurContext
;
18864 // Skip past RequiresExprBodys because they don't constitute function scopes.
18865 while (DC
->isRequiresExprBody())
18866 DC
= DC
->getParent();
18868 // tryCaptureVariable is called every time a DeclRef is formed,
18869 // it can therefore have non-negigible impact on performances.
18870 // For local variables and when there is no capturing scope,
18871 // we can bailout early.
18872 if (CapturingFunctionScopes
== 0 && (!BuildAndDiagnose
|| VarDC
== DC
))
18875 // Exception: Function parameters are not tied to the function's DeclContext
18876 // until we enter the function definition. Capturing them anyway would result
18877 // in an out-of-bounds error while traversing DC and its parents.
18878 if (isa
<ParmVarDecl
>(Var
) && !VarDC
->isFunctionOrMethod())
18881 const auto *VD
= dyn_cast
<VarDecl
>(Var
);
18883 if (VD
->isInitCapture())
18884 VarDC
= VarDC
->getParent();
18886 VD
= Var
->getPotentiallyDecomposedVarDecl();
18888 assert(VD
&& "Cannot capture a null variable");
18890 const unsigned MaxFunctionScopesIndex
= FunctionScopeIndexToStopAt
18891 ? *FunctionScopeIndexToStopAt
: FunctionScopes
.size() - 1;
18892 // We need to sync up the Declaration Context with the
18893 // FunctionScopeIndexToStopAt
18894 if (FunctionScopeIndexToStopAt
) {
18895 assert(!FunctionScopes
.empty() && "No function scopes to stop at?");
18896 unsigned FSIndex
= FunctionScopes
.size() - 1;
18897 // When we're parsing the lambda parameter list, the current DeclContext is
18898 // NOT the lambda but its parent. So move away the current LSI before
18899 // aligning DC and FunctionScopeIndexToStopAt.
18900 if (auto *LSI
= dyn_cast
<LambdaScopeInfo
>(FunctionScopes
[FSIndex
]);
18901 FSIndex
&& LSI
&& !LSI
->AfterParameterList
)
18903 assert(MaxFunctionScopesIndex
<= FSIndex
&&
18904 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
18905 "FunctionScopes.");
18906 while (FSIndex
!= MaxFunctionScopesIndex
) {
18907 DC
= getLambdaAwareParentOfDeclContext(DC
);
18912 // Capture global variables if it is required to use private copy of this
18914 bool IsGlobal
= !VD
->hasLocalStorage();
18915 if (IsGlobal
&& !(LangOpts
.OpenMP
&&
18916 OpenMP().isOpenMPCapturedDecl(Var
, /*CheckScopeInfo=*/true,
18917 MaxFunctionScopesIndex
)))
18920 if (isa
<VarDecl
>(Var
))
18921 Var
= cast
<VarDecl
>(Var
->getCanonicalDecl());
18923 // Walk up the stack to determine whether we can capture the variable,
18924 // performing the "simple" checks that don't depend on type. We stop when
18925 // we've either hit the declared scope of the variable or find an existing
18926 // capture of that variable. We start from the innermost capturing-entity
18927 // (the DC) and ensure that all intervening capturing-entities
18928 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
18929 // declcontext can either capture the variable or have already captured
18931 CaptureType
= Var
->getType();
18932 DeclRefType
= CaptureType
.getNonReferenceType();
18933 bool Nested
= false;
18934 bool Explicit
= (Kind
!= TryCapture_Implicit
);
18935 unsigned FunctionScopesIndex
= MaxFunctionScopesIndex
;
18938 LambdaScopeInfo
*LSI
= nullptr;
18939 if (!FunctionScopes
.empty())
18940 LSI
= dyn_cast_or_null
<LambdaScopeInfo
>(
18941 FunctionScopes
[FunctionScopesIndex
]);
18943 bool IsInScopeDeclarationContext
=
18944 !LSI
|| LSI
->AfterParameterList
|| CurContext
== LSI
->CallOperator
;
18946 if (LSI
&& !LSI
->AfterParameterList
) {
18947 // This allows capturing parameters from a default value which does not
18949 if (isa
<ParmVarDecl
>(Var
) && !Var
->getDeclContext()->isFunctionOrMethod())
18952 // If the variable is declared in the current context, there is no need to
18954 if (IsInScopeDeclarationContext
&&
18955 FunctionScopesIndex
== MaxFunctionScopesIndex
&& VarDC
== DC
)
18958 // Only block literals, captured statements, and lambda expressions can
18959 // capture; other scopes don't work.
18960 DeclContext
*ParentDC
=
18961 !IsInScopeDeclarationContext
18963 : getParentOfCapturingContextOrNull(DC
, Var
, ExprLoc
,
18964 BuildAndDiagnose
, *this);
18965 // We need to check for the parent *first* because, if we *have*
18966 // private-captured a global variable, we need to recursively capture it in
18967 // intermediate blocks, lambdas, etc.
18970 FunctionScopesIndex
= MaxFunctionScopesIndex
- 1;
18976 FunctionScopeInfo
*FSI
= FunctionScopes
[FunctionScopesIndex
];
18977 CapturingScopeInfo
*CSI
= cast
<CapturingScopeInfo
>(FSI
);
18979 // Check whether we've already captured it.
18980 if (isVariableAlreadyCapturedInScopeInfo(CSI
, Var
, Nested
, CaptureType
,
18982 CSI
->getCapture(Var
).markUsed(BuildAndDiagnose
);
18986 // When evaluating some attributes (like enable_if) we might refer to a
18987 // function parameter appertaining to the same declaration as that
18989 if (const auto *Parm
= dyn_cast
<ParmVarDecl
>(Var
);
18990 Parm
&& Parm
->getDeclContext() == DC
)
18993 // If we are instantiating a generic lambda call operator body,
18994 // we do not want to capture new variables. What was captured
18995 // during either a lambdas transformation or initial parsing
18997 if (isGenericLambdaCallOperatorSpecialization(DC
)) {
18998 if (BuildAndDiagnose
) {
18999 LambdaScopeInfo
*LSI
= cast
<LambdaScopeInfo
>(CSI
);
19000 if (LSI
->ImpCaptureStyle
== CapturingScopeInfo::ImpCap_None
) {
19001 Diag(ExprLoc
, diag::err_lambda_impcap
) << Var
;
19002 Diag(Var
->getLocation(), diag::note_previous_decl
) << Var
;
19003 Diag(LSI
->Lambda
->getBeginLoc(), diag::note_lambda_decl
);
19004 buildLambdaCaptureFixit(*this, LSI
, Var
);
19006 diagnoseUncapturableValueReferenceOrBinding(*this, ExprLoc
, Var
);
19011 // Try to capture variable-length arrays types.
19012 if (Var
->getType()->isVariablyModifiedType()) {
19013 // We're going to walk down into the type and look for VLA
19015 QualType QTy
= Var
->getType();
19016 if (ParmVarDecl
*PVD
= dyn_cast_or_null
<ParmVarDecl
>(Var
))
19017 QTy
= PVD
->getOriginalType();
19018 captureVariablyModifiedType(Context
, QTy
, CSI
);
19021 if (getLangOpts().OpenMP
) {
19022 if (auto *RSI
= dyn_cast
<CapturedRegionScopeInfo
>(CSI
)) {
19023 // OpenMP private variables should not be captured in outer scope, so
19024 // just break here. Similarly, global variables that are captured in a
19025 // target region should not be captured outside the scope of the region.
19026 if (RSI
->CapRegionKind
== CR_OpenMP
) {
19027 // FIXME: We should support capturing structured bindings in OpenMP.
19028 if (isa
<BindingDecl
>(Var
)) {
19029 if (BuildAndDiagnose
) {
19030 Diag(ExprLoc
, diag::err_capture_binding_openmp
) << Var
;
19031 Diag(Var
->getLocation(), diag::note_entity_declared_at
) << Var
;
19035 OpenMPClauseKind IsOpenMPPrivateDecl
= OpenMP().isOpenMPPrivateDecl(
19036 Var
, RSI
->OpenMPLevel
, RSI
->OpenMPCaptureLevel
);
19037 // If the variable is private (i.e. not captured) and has variably
19038 // modified type, we still need to capture the type for correct
19039 // codegen in all regions, associated with the construct. Currently,
19040 // it is captured in the innermost captured region only.
19041 if (IsOpenMPPrivateDecl
!= OMPC_unknown
&&
19042 Var
->getType()->isVariablyModifiedType()) {
19043 QualType QTy
= Var
->getType();
19044 if (ParmVarDecl
*PVD
= dyn_cast_or_null
<ParmVarDecl
>(Var
))
19045 QTy
= PVD
->getOriginalType();
19047 E
= OpenMP().getNumberOfConstructScopes(RSI
->OpenMPLevel
);
19049 auto *OuterRSI
= cast
<CapturedRegionScopeInfo
>(
19050 FunctionScopes
[FunctionScopesIndex
- I
]);
19051 assert(RSI
->OpenMPLevel
== OuterRSI
->OpenMPLevel
&&
19052 "Wrong number of captured regions associated with the "
19053 "OpenMP construct.");
19054 captureVariablyModifiedType(Context
, QTy
, OuterRSI
);
19058 IsOpenMPPrivateDecl
!= OMPC_private
&&
19059 OpenMP().isOpenMPTargetCapturedDecl(Var
, RSI
->OpenMPLevel
,
19060 RSI
->OpenMPCaptureLevel
);
19061 // Do not capture global if it is not privatized in outer regions.
19063 IsGlobal
&& OpenMP().isOpenMPGlobalCapturedDecl(
19064 Var
, RSI
->OpenMPLevel
, RSI
->OpenMPCaptureLevel
);
19066 // When we detect target captures we are looking from inside the
19067 // target region, therefore we need to propagate the capture from the
19068 // enclosing region. Therefore, the capture is not initially nested.
19070 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex
,
19073 if (IsTargetCap
|| IsOpenMPPrivateDecl
== OMPC_private
||
19074 (IsGlobal
&& !IsGlobalCap
)) {
19075 Nested
= !IsTargetCap
;
19076 bool HasConst
= DeclRefType
.isConstQualified();
19077 DeclRefType
= DeclRefType
.getUnqualifiedType();
19078 // Don't lose diagnostics about assignments to const.
19080 DeclRefType
.addConst();
19081 CaptureType
= Context
.getLValueReferenceType(DeclRefType
);
19087 if (CSI
->ImpCaptureStyle
== CapturingScopeInfo::ImpCap_None
&& !Explicit
) {
19088 // No capture-default, and this is not an explicit capture
19089 // so cannot capture this variable.
19090 if (BuildAndDiagnose
) {
19091 Diag(ExprLoc
, diag::err_lambda_impcap
) << Var
;
19092 Diag(Var
->getLocation(), diag::note_previous_decl
) << Var
;
19093 auto *LSI
= cast
<LambdaScopeInfo
>(CSI
);
19095 Diag(LSI
->Lambda
->getBeginLoc(), diag::note_lambda_decl
);
19096 buildLambdaCaptureFixit(*this, LSI
, Var
);
19098 // FIXME: If we error out because an outer lambda can not implicitly
19099 // capture a variable that an inner lambda explicitly captures, we
19100 // should have the inner lambda do the explicit capture - because
19101 // it makes for cleaner diagnostics later. This would purely be done
19102 // so that the diagnostic does not misleadingly claim that a variable
19103 // can not be captured by a lambda implicitly even though it is captured
19104 // explicitly. Suggestion:
19105 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19106 // at the function head
19107 // - cache the StartingDeclContext - this must be a lambda
19108 // - captureInLambda in the innermost lambda the variable.
19113 FunctionScopesIndex
--;
19114 if (IsInScopeDeclarationContext
)
19116 } while (!VarDC
->Equals(DC
));
19118 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19119 // computing the type of the capture at each step, checking type-specific
19120 // requirements, and adding captures if requested.
19121 // If the variable had already been captured previously, we start capturing
19122 // at the lambda nested within that one.
19123 bool Invalid
= false;
19124 for (unsigned I
= ++FunctionScopesIndex
, N
= MaxFunctionScopesIndex
+ 1; I
!= N
;
19126 CapturingScopeInfo
*CSI
= cast
<CapturingScopeInfo
>(FunctionScopes
[I
]);
19128 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19129 // certain types of variables (unnamed, variably modified types etc.)
19130 // so check for eligibility.
19133 !isVariableCapturable(CSI
, Var
, ExprLoc
, BuildAndDiagnose
, *this);
19135 // After encountering an error, if we're actually supposed to capture, keep
19136 // capturing in nested contexts to suppress any follow-on diagnostics.
19137 if (Invalid
&& !BuildAndDiagnose
)
19140 if (BlockScopeInfo
*BSI
= dyn_cast
<BlockScopeInfo
>(CSI
)) {
19141 Invalid
= !captureInBlock(BSI
, Var
, ExprLoc
, BuildAndDiagnose
, CaptureType
,
19142 DeclRefType
, Nested
, *this, Invalid
);
19144 } else if (CapturedRegionScopeInfo
*RSI
= dyn_cast
<CapturedRegionScopeInfo
>(CSI
)) {
19145 Invalid
= !captureInCapturedRegion(
19146 RSI
, Var
, ExprLoc
, BuildAndDiagnose
, CaptureType
, DeclRefType
, Nested
,
19147 Kind
, /*IsTopScope*/ I
== N
- 1, *this, Invalid
);
19150 LambdaScopeInfo
*LSI
= cast
<LambdaScopeInfo
>(CSI
);
19152 !captureInLambda(LSI
, Var
, ExprLoc
, BuildAndDiagnose
, CaptureType
,
19153 DeclRefType
, Nested
, Kind
, EllipsisLoc
,
19154 /*IsTopScope*/ I
== N
- 1, *this, Invalid
);
19158 if (Invalid
&& !BuildAndDiagnose
)
19164 bool Sema::tryCaptureVariable(ValueDecl
*Var
, SourceLocation Loc
,
19165 TryCaptureKind Kind
, SourceLocation EllipsisLoc
) {
19166 QualType CaptureType
;
19167 QualType DeclRefType
;
19168 return tryCaptureVariable(Var
, Loc
, Kind
, EllipsisLoc
,
19169 /*BuildAndDiagnose=*/true, CaptureType
,
19170 DeclRefType
, nullptr);
19173 bool Sema::NeedToCaptureVariable(ValueDecl
*Var
, SourceLocation Loc
) {
19174 QualType CaptureType
;
19175 QualType DeclRefType
;
19176 return !tryCaptureVariable(Var
, Loc
, TryCapture_Implicit
, SourceLocation(),
19177 /*BuildAndDiagnose=*/false, CaptureType
,
19178 DeclRefType
, nullptr);
19181 QualType
Sema::getCapturedDeclRefType(ValueDecl
*Var
, SourceLocation Loc
) {
19182 QualType CaptureType
;
19183 QualType DeclRefType
;
19185 // Determine whether we can capture this variable.
19186 if (tryCaptureVariable(Var
, Loc
, TryCapture_Implicit
, SourceLocation(),
19187 /*BuildAndDiagnose=*/false, CaptureType
,
19188 DeclRefType
, nullptr))
19191 return DeclRefType
;
19195 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19196 // The produced TemplateArgumentListInfo* points to data stored within this
19197 // object, so should only be used in contexts where the pointer will not be
19198 // used after the CopiedTemplateArgs object is destroyed.
19199 class CopiedTemplateArgs
{
19201 TemplateArgumentListInfo TemplateArgStorage
;
19203 template<typename RefExpr
>
19204 CopiedTemplateArgs(RefExpr
*E
) : HasArgs(E
->hasExplicitTemplateArgs()) {
19206 E
->copyTemplateArgumentsInto(TemplateArgStorage
);
19208 operator TemplateArgumentListInfo
*()
19209 #ifdef __has_cpp_attribute
19210 #if __has_cpp_attribute(clang::lifetimebound)
19211 [[clang::lifetimebound
]]
19215 return HasArgs
? &TemplateArgStorage
: nullptr;
19220 /// Walk the set of potential results of an expression and mark them all as
19221 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19223 /// \return A new expression if we found any potential results, ExprEmpty() if
19224 /// not, and ExprError() if we diagnosed an error.
19225 static ExprResult
rebuildPotentialResultsAsNonOdrUsed(Sema
&S
, Expr
*E
,
19226 NonOdrUseReason NOUR
) {
19227 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19228 // an object that satisfies the requirements for appearing in a
19229 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19230 // is immediately applied." This function handles the lvalue-to-rvalue
19231 // conversion part.
19233 // If we encounter a node that claims to be an odr-use but shouldn't be, we
19234 // transform it into the relevant kind of non-odr-use node and rebuild the
19235 // tree of nodes leading to it.
19237 // This is a mini-TreeTransform that only transforms a restricted subset of
19238 // nodes (and only certain operands of them).
19240 // Rebuild a subexpression.
19241 auto Rebuild
= [&](Expr
*Sub
) {
19242 return rebuildPotentialResultsAsNonOdrUsed(S
, Sub
, NOUR
);
19245 // Check whether a potential result satisfies the requirements of NOUR.
19246 auto IsPotentialResultOdrUsed
= [&](NamedDecl
*D
) {
19247 // Any entity other than a VarDecl is always odr-used whenever it's named
19248 // in a potentially-evaluated expression.
19249 auto *VD
= dyn_cast
<VarDecl
>(D
);
19253 // C++2a [basic.def.odr]p4:
19254 // A variable x whose name appears as a potentially-evalauted expression
19255 // e is odr-used by e unless
19256 // -- x is a reference that is usable in constant expressions, or
19257 // -- x is a variable of non-reference type that is usable in constant
19258 // expressions and has no mutable subobjects, and e is an element of
19259 // the set of potential results of an expression of
19260 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19261 // conversion is applied, or
19262 // -- x is a variable of non-reference type, and e is an element of the
19263 // set of potential results of a discarded-value expression to which
19264 // the lvalue-to-rvalue conversion is not applied
19266 // We check the first bullet and the "potentially-evaluated" condition in
19267 // BuildDeclRefExpr. We check the type requirements in the second bullet
19268 // in CheckLValueToRValueConversionOperand below.
19271 case NOUR_Unevaluated
:
19272 llvm_unreachable("unexpected non-odr-use-reason");
19274 case NOUR_Constant
:
19275 // Constant references were handled when they were built.
19276 if (VD
->getType()->isReferenceType())
19278 if (auto *RD
= VD
->getType()->getAsCXXRecordDecl())
19279 if (RD
->hasMutableFields())
19281 if (!VD
->isUsableInConstantExpressions(S
.Context
))
19285 case NOUR_Discarded
:
19286 if (VD
->getType()->isReferenceType())
19293 // Mark that this expression does not constitute an odr-use.
19294 auto MarkNotOdrUsed
= [&] {
19295 S
.MaybeODRUseExprs
.remove(E
);
19296 if (LambdaScopeInfo
*LSI
= S
.getCurLambda())
19297 LSI
->markVariableExprAsNonODRUsed(E
);
19300 // C++2a [basic.def.odr]p2:
19301 // The set of potential results of an expression e is defined as follows:
19302 switch (E
->getStmtClass()) {
19303 // -- If e is an id-expression, ...
19304 case Expr::DeclRefExprClass
: {
19305 auto *DRE
= cast
<DeclRefExpr
>(E
);
19306 if (DRE
->isNonOdrUse() || IsPotentialResultOdrUsed(DRE
->getDecl()))
19309 // Rebuild as a non-odr-use DeclRefExpr.
19311 return DeclRefExpr::Create(
19312 S
.Context
, DRE
->getQualifierLoc(), DRE
->getTemplateKeywordLoc(),
19313 DRE
->getDecl(), DRE
->refersToEnclosingVariableOrCapture(),
19314 DRE
->getNameInfo(), DRE
->getType(), DRE
->getValueKind(),
19315 DRE
->getFoundDecl(), CopiedTemplateArgs(DRE
), NOUR
);
19318 case Expr::FunctionParmPackExprClass
: {
19319 auto *FPPE
= cast
<FunctionParmPackExpr
>(E
);
19320 // If any of the declarations in the pack is odr-used, then the expression
19321 // as a whole constitutes an odr-use.
19322 for (VarDecl
*D
: *FPPE
)
19323 if (IsPotentialResultOdrUsed(D
))
19324 return ExprEmpty();
19326 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19327 // nothing cares about whether we marked this as an odr-use, but it might
19328 // be useful for non-compiler tools.
19333 // -- If e is a subscripting operation with an array operand...
19334 case Expr::ArraySubscriptExprClass
: {
19335 auto *ASE
= cast
<ArraySubscriptExpr
>(E
);
19336 Expr
*OldBase
= ASE
->getBase()->IgnoreImplicit();
19337 if (!OldBase
->getType()->isArrayType())
19339 ExprResult Base
= Rebuild(OldBase
);
19340 if (!Base
.isUsable())
19342 Expr
*LHS
= ASE
->getBase() == ASE
->getLHS() ? Base
.get() : ASE
->getLHS();
19343 Expr
*RHS
= ASE
->getBase() == ASE
->getRHS() ? Base
.get() : ASE
->getRHS();
19344 SourceLocation LBracketLoc
= ASE
->getBeginLoc(); // FIXME: Not stored.
19345 return S
.ActOnArraySubscriptExpr(nullptr, LHS
, LBracketLoc
, RHS
,
19346 ASE
->getRBracketLoc());
19349 case Expr::MemberExprClass
: {
19350 auto *ME
= cast
<MemberExpr
>(E
);
19351 // -- If e is a class member access expression [...] naming a non-static
19353 if (isa
<FieldDecl
>(ME
->getMemberDecl())) {
19354 ExprResult Base
= Rebuild(ME
->getBase());
19355 if (!Base
.isUsable())
19357 return MemberExpr::Create(
19358 S
.Context
, Base
.get(), ME
->isArrow(), ME
->getOperatorLoc(),
19359 ME
->getQualifierLoc(), ME
->getTemplateKeywordLoc(),
19360 ME
->getMemberDecl(), ME
->getFoundDecl(), ME
->getMemberNameInfo(),
19361 CopiedTemplateArgs(ME
), ME
->getType(), ME
->getValueKind(),
19362 ME
->getObjectKind(), ME
->isNonOdrUse());
19365 if (ME
->getMemberDecl()->isCXXInstanceMember())
19368 // -- If e is a class member access expression naming a static data member,
19370 if (ME
->isNonOdrUse() || IsPotentialResultOdrUsed(ME
->getMemberDecl()))
19373 // Rebuild as a non-odr-use MemberExpr.
19375 return MemberExpr::Create(
19376 S
.Context
, ME
->getBase(), ME
->isArrow(), ME
->getOperatorLoc(),
19377 ME
->getQualifierLoc(), ME
->getTemplateKeywordLoc(), ME
->getMemberDecl(),
19378 ME
->getFoundDecl(), ME
->getMemberNameInfo(), CopiedTemplateArgs(ME
),
19379 ME
->getType(), ME
->getValueKind(), ME
->getObjectKind(), NOUR
);
19382 case Expr::BinaryOperatorClass
: {
19383 auto *BO
= cast
<BinaryOperator
>(E
);
19384 Expr
*LHS
= BO
->getLHS();
19385 Expr
*RHS
= BO
->getRHS();
19386 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19387 if (BO
->getOpcode() == BO_PtrMemD
) {
19388 ExprResult Sub
= Rebuild(LHS
);
19389 if (!Sub
.isUsable())
19391 BO
->setLHS(Sub
.get());
19392 // -- If e is a comma expression, ...
19393 } else if (BO
->getOpcode() == BO_Comma
) {
19394 ExprResult Sub
= Rebuild(RHS
);
19395 if (!Sub
.isUsable())
19397 BO
->setRHS(Sub
.get());
19401 return ExprResult(BO
);
19404 // -- If e has the form (e1)...
19405 case Expr::ParenExprClass
: {
19406 auto *PE
= cast
<ParenExpr
>(E
);
19407 ExprResult Sub
= Rebuild(PE
->getSubExpr());
19408 if (!Sub
.isUsable())
19410 return S
.ActOnParenExpr(PE
->getLParen(), PE
->getRParen(), Sub
.get());
19413 // -- If e is a glvalue conditional expression, ...
19414 // We don't apply this to a binary conditional operator. FIXME: Should we?
19415 case Expr::ConditionalOperatorClass
: {
19416 auto *CO
= cast
<ConditionalOperator
>(E
);
19417 ExprResult LHS
= Rebuild(CO
->getLHS());
19418 if (LHS
.isInvalid())
19419 return ExprError();
19420 ExprResult RHS
= Rebuild(CO
->getRHS());
19421 if (RHS
.isInvalid())
19422 return ExprError();
19423 if (!LHS
.isUsable() && !RHS
.isUsable())
19424 return ExprEmpty();
19425 if (!LHS
.isUsable())
19426 LHS
= CO
->getLHS();
19427 if (!RHS
.isUsable())
19428 RHS
= CO
->getRHS();
19429 return S
.ActOnConditionalOp(CO
->getQuestionLoc(), CO
->getColonLoc(),
19430 CO
->getCond(), LHS
.get(), RHS
.get());
19433 // [Clang extension]
19434 // -- If e has the form __extension__ e1...
19435 case Expr::UnaryOperatorClass
: {
19436 auto *UO
= cast
<UnaryOperator
>(E
);
19437 if (UO
->getOpcode() != UO_Extension
)
19439 ExprResult Sub
= Rebuild(UO
->getSubExpr());
19440 if (!Sub
.isUsable())
19442 return S
.BuildUnaryOp(nullptr, UO
->getOperatorLoc(), UO_Extension
,
19446 // [Clang extension]
19447 // -- If e has the form _Generic(...), the set of potential results is the
19448 // union of the sets of potential results of the associated expressions.
19449 case Expr::GenericSelectionExprClass
: {
19450 auto *GSE
= cast
<GenericSelectionExpr
>(E
);
19452 SmallVector
<Expr
*, 4> AssocExprs
;
19453 bool AnyChanged
= false;
19454 for (Expr
*OrigAssocExpr
: GSE
->getAssocExprs()) {
19455 ExprResult AssocExpr
= Rebuild(OrigAssocExpr
);
19456 if (AssocExpr
.isInvalid())
19457 return ExprError();
19458 if (AssocExpr
.isUsable()) {
19459 AssocExprs
.push_back(AssocExpr
.get());
19462 AssocExprs
.push_back(OrigAssocExpr
);
19466 void *ExOrTy
= nullptr;
19467 bool IsExpr
= GSE
->isExprPredicate();
19469 ExOrTy
= GSE
->getControllingExpr();
19471 ExOrTy
= GSE
->getControllingType();
19472 return AnyChanged
? S
.CreateGenericSelectionExpr(
19473 GSE
->getGenericLoc(), GSE
->getDefaultLoc(),
19474 GSE
->getRParenLoc(), IsExpr
, ExOrTy
,
19475 GSE
->getAssocTypeSourceInfos(), AssocExprs
)
19479 // [Clang extension]
19480 // -- If e has the form __builtin_choose_expr(...), the set of potential
19481 // results is the union of the sets of potential results of the
19482 // second and third subexpressions.
19483 case Expr::ChooseExprClass
: {
19484 auto *CE
= cast
<ChooseExpr
>(E
);
19486 ExprResult LHS
= Rebuild(CE
->getLHS());
19487 if (LHS
.isInvalid())
19488 return ExprError();
19490 ExprResult RHS
= Rebuild(CE
->getLHS());
19491 if (RHS
.isInvalid())
19492 return ExprError();
19494 if (!LHS
.get() && !RHS
.get())
19495 return ExprEmpty();
19496 if (!LHS
.isUsable())
19497 LHS
= CE
->getLHS();
19498 if (!RHS
.isUsable())
19499 RHS
= CE
->getRHS();
19501 return S
.ActOnChooseExpr(CE
->getBuiltinLoc(), CE
->getCond(), LHS
.get(),
19502 RHS
.get(), CE
->getRParenLoc());
19505 // Step through non-syntactic nodes.
19506 case Expr::ConstantExprClass
: {
19507 auto *CE
= cast
<ConstantExpr
>(E
);
19508 ExprResult Sub
= Rebuild(CE
->getSubExpr());
19509 if (!Sub
.isUsable())
19511 return ConstantExpr::Create(S
.Context
, Sub
.get());
19514 // We could mostly rely on the recursive rebuilding to rebuild implicit
19515 // casts, but not at the top level, so rebuild them here.
19516 case Expr::ImplicitCastExprClass
: {
19517 auto *ICE
= cast
<ImplicitCastExpr
>(E
);
19518 // Only step through the narrow set of cast kinds we expect to encounter.
19519 // Anything else suggests we've left the region in which potential results
19521 switch (ICE
->getCastKind()) {
19523 case CK_DerivedToBase
:
19524 case CK_UncheckedDerivedToBase
: {
19525 ExprResult Sub
= Rebuild(ICE
->getSubExpr());
19526 if (!Sub
.isUsable())
19528 CXXCastPath
Path(ICE
->path());
19529 return S
.ImpCastExprToType(Sub
.get(), ICE
->getType(), ICE
->getCastKind(),
19530 ICE
->getValueKind(), &Path
);
19543 // Can't traverse through this node. Nothing to do.
19544 return ExprEmpty();
19547 ExprResult
Sema::CheckLValueToRValueConversionOperand(Expr
*E
) {
19548 // Check whether the operand is or contains an object of non-trivial C union
19550 if (E
->getType().isVolatileQualified() &&
19551 (E
->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
19552 E
->getType().hasNonTrivialToPrimitiveCopyCUnion()))
19553 checkNonTrivialCUnion(E
->getType(), E
->getExprLoc(),
19554 Sema::NTCUC_LValueToRValueVolatile
,
19555 NTCUK_Destruct
|NTCUK_Copy
);
19557 // C++2a [basic.def.odr]p4:
19558 // [...] an expression of non-volatile-qualified non-class type to which
19559 // the lvalue-to-rvalue conversion is applied [...]
19560 if (E
->getType().isVolatileQualified() || E
->getType()->getAs
<RecordType
>())
19563 ExprResult Result
=
19564 rebuildPotentialResultsAsNonOdrUsed(*this, E
, NOUR_Constant
);
19565 if (Result
.isInvalid())
19566 return ExprError();
19567 return Result
.get() ? Result
: E
;
19570 ExprResult
Sema::ActOnConstantExpression(ExprResult Res
) {
19571 Res
= CorrectDelayedTyposInExpr(Res
);
19573 if (!Res
.isUsable())
19576 // If a constant-expression is a reference to a variable where we delay
19577 // deciding whether it is an odr-use, just assume we will apply the
19578 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
19579 // (a non-type template argument), we have special handling anyway.
19580 return CheckLValueToRValueConversionOperand(Res
.get());
19583 void Sema::CleanupVarDeclMarking() {
19584 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19586 MaybeODRUseExprSet LocalMaybeODRUseExprs
;
19587 std::swap(LocalMaybeODRUseExprs
, MaybeODRUseExprs
);
19589 for (Expr
*E
: LocalMaybeODRUseExprs
) {
19590 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(E
)) {
19591 MarkVarDeclODRUsed(cast
<VarDecl
>(DRE
->getDecl()),
19592 DRE
->getLocation(), *this);
19593 } else if (auto *ME
= dyn_cast
<MemberExpr
>(E
)) {
19594 MarkVarDeclODRUsed(cast
<VarDecl
>(ME
->getMemberDecl()), ME
->getMemberLoc(),
19596 } else if (auto *FP
= dyn_cast
<FunctionParmPackExpr
>(E
)) {
19597 for (VarDecl
*VD
: *FP
)
19598 MarkVarDeclODRUsed(VD
, FP
->getParameterPackLocation(), *this);
19600 llvm_unreachable("Unexpected expression");
19604 assert(MaybeODRUseExprs
.empty() &&
19605 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
19608 static void DoMarkPotentialCapture(Sema
&SemaRef
, SourceLocation Loc
,
19609 ValueDecl
*Var
, Expr
*E
) {
19610 VarDecl
*VD
= Var
->getPotentiallyDecomposedVarDecl();
19614 const bool RefersToEnclosingScope
=
19615 (SemaRef
.CurContext
!= VD
->getDeclContext() &&
19616 VD
->getDeclContext()->isFunctionOrMethod() && VD
->hasLocalStorage());
19617 if (RefersToEnclosingScope
) {
19618 LambdaScopeInfo
*const LSI
=
19619 SemaRef
.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19620 if (LSI
&& (!LSI
->CallOperator
||
19621 !LSI
->CallOperator
->Encloses(Var
->getDeclContext()))) {
19622 // If a variable could potentially be odr-used, defer marking it so
19623 // until we finish analyzing the full expression for any
19624 // lvalue-to-rvalue
19625 // or discarded value conversions that would obviate odr-use.
19626 // Add it to the list of potential captures that will be analyzed
19627 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19628 // unless the variable is a reference that was initialized by a constant
19629 // expression (this will never need to be captured or odr-used).
19631 // FIXME: We can simplify this a lot after implementing P0588R1.
19632 assert(E
&& "Capture variable should be used in an expression.");
19633 if (!Var
->getType()->isReferenceType() ||
19634 !VD
->isUsableInConstantExpressions(SemaRef
.Context
))
19635 LSI
->addPotentialCapture(E
->IgnoreParens());
19640 static void DoMarkVarDeclReferenced(
19641 Sema
&SemaRef
, SourceLocation Loc
, VarDecl
*Var
, Expr
*E
,
19642 llvm::DenseMap
<const VarDecl
*, int> &RefsMinusAssignments
) {
19643 assert((!E
|| isa
<DeclRefExpr
>(E
) || isa
<MemberExpr
>(E
) ||
19644 isa
<FunctionParmPackExpr
>(E
)) &&
19645 "Invalid Expr argument to DoMarkVarDeclReferenced");
19646 Var
->setReferenced();
19648 if (Var
->isInvalidDecl())
19651 auto *MSI
= Var
->getMemberSpecializationInfo();
19652 TemplateSpecializationKind TSK
= MSI
? MSI
->getTemplateSpecializationKind()
19653 : Var
->getTemplateSpecializationKind();
19655 OdrUseContext OdrUse
= isOdrUseContext(SemaRef
);
19656 bool UsableInConstantExpr
=
19657 Var
->mightBeUsableInConstantExpressions(SemaRef
.Context
);
19659 if (Var
->isLocalVarDeclOrParm() && !Var
->hasExternalStorage()) {
19660 RefsMinusAssignments
.insert({Var
, 0}).first
->getSecond()++;
19663 // C++20 [expr.const]p12:
19664 // A variable [...] is needed for constant evaluation if it is [...] a
19665 // variable whose name appears as a potentially constant evaluated
19666 // expression that is either a contexpr variable or is of non-volatile
19667 // const-qualified integral type or of reference type
19668 bool NeededForConstantEvaluation
=
19669 isPotentiallyConstantEvaluatedContext(SemaRef
) && UsableInConstantExpr
;
19671 bool NeedDefinition
=
19672 OdrUse
== OdrUseContext::Used
|| NeededForConstantEvaluation
;
19674 assert(!isa
<VarTemplatePartialSpecializationDecl
>(Var
) &&
19675 "Can't instantiate a partial template specialization.");
19677 // If this might be a member specialization of a static data member, check
19678 // the specialization is visible. We already did the checks for variable
19679 // template specializations when we created them.
19680 if (NeedDefinition
&& TSK
!= TSK_Undeclared
&&
19681 !isa
<VarTemplateSpecializationDecl
>(Var
))
19682 SemaRef
.checkSpecializationVisibility(Loc
, Var
);
19684 // Perform implicit instantiation of static data members, static data member
19685 // templates of class templates, and variable template specializations. Delay
19686 // instantiations of variable templates, except for those that could be used
19687 // in a constant expression.
19688 if (NeedDefinition
&& isTemplateInstantiation(TSK
)) {
19689 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
19690 // instantiation declaration if a variable is usable in a constant
19691 // expression (among other cases).
19692 bool TryInstantiating
=
19693 TSK
== TSK_ImplicitInstantiation
||
19694 (TSK
== TSK_ExplicitInstantiationDeclaration
&& UsableInConstantExpr
);
19696 if (TryInstantiating
) {
19697 SourceLocation PointOfInstantiation
=
19698 MSI
? MSI
->getPointOfInstantiation() : Var
->getPointOfInstantiation();
19699 bool FirstInstantiation
= PointOfInstantiation
.isInvalid();
19700 if (FirstInstantiation
) {
19701 PointOfInstantiation
= Loc
;
19703 MSI
->setPointOfInstantiation(PointOfInstantiation
);
19704 // FIXME: Notify listener.
19706 Var
->setTemplateSpecializationKind(TSK
, PointOfInstantiation
);
19709 if (UsableInConstantExpr
) {
19710 // Do not defer instantiations of variables that could be used in a
19711 // constant expression.
19712 SemaRef
.runWithSufficientStackSpace(PointOfInstantiation
, [&] {
19713 SemaRef
.InstantiateVariableDefinition(PointOfInstantiation
, Var
);
19716 // Re-set the member to trigger a recomputation of the dependence bits
19717 // for the expression.
19718 if (auto *DRE
= dyn_cast_or_null
<DeclRefExpr
>(E
))
19719 DRE
->setDecl(DRE
->getDecl());
19720 else if (auto *ME
= dyn_cast_or_null
<MemberExpr
>(E
))
19721 ME
->setMemberDecl(ME
->getMemberDecl());
19722 } else if (FirstInstantiation
) {
19723 SemaRef
.PendingInstantiations
19724 .push_back(std::make_pair(Var
, PointOfInstantiation
));
19726 bool Inserted
= false;
19727 for (auto &I
: SemaRef
.SavedPendingInstantiations
) {
19728 auto Iter
= llvm::find_if(
19729 I
, [Var
](const Sema::PendingImplicitInstantiation
&P
) {
19730 return P
.first
== Var
;
19732 if (Iter
!= I
.end()) {
19733 SemaRef
.PendingInstantiations
.push_back(*Iter
);
19740 // FIXME: For a specialization of a variable template, we don't
19741 // distinguish between "declaration and type implicitly instantiated"
19742 // and "implicit instantiation of definition requested", so we have
19743 // no direct way to avoid enqueueing the pending instantiation
19745 if (isa
<VarTemplateSpecializationDecl
>(Var
) && !Inserted
)
19746 SemaRef
.PendingInstantiations
19747 .push_back(std::make_pair(Var
, PointOfInstantiation
));
19752 // C++2a [basic.def.odr]p4:
19753 // A variable x whose name appears as a potentially-evaluated expression e
19754 // is odr-used by e unless
19755 // -- x is a reference that is usable in constant expressions
19756 // -- x is a variable of non-reference type that is usable in constant
19757 // expressions and has no mutable subobjects [FIXME], and e is an
19758 // element of the set of potential results of an expression of
19759 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19760 // conversion is applied
19761 // -- x is a variable of non-reference type, and e is an element of the set
19762 // of potential results of a discarded-value expression to which the
19763 // lvalue-to-rvalue conversion is not applied [FIXME]
19765 // We check the first part of the second bullet here, and
19766 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
19767 // FIXME: To get the third bullet right, we need to delay this even for
19768 // variables that are not usable in constant expressions.
19770 // If we already know this isn't an odr-use, there's nothing more to do.
19771 if (DeclRefExpr
*DRE
= dyn_cast_or_null
<DeclRefExpr
>(E
))
19772 if (DRE
->isNonOdrUse())
19774 if (MemberExpr
*ME
= dyn_cast_or_null
<MemberExpr
>(E
))
19775 if (ME
->isNonOdrUse())
19779 case OdrUseContext::None
:
19780 // In some cases, a variable may not have been marked unevaluated, if it
19781 // appears in a defaukt initializer.
19782 assert((!E
|| isa
<FunctionParmPackExpr
>(E
) ||
19783 SemaRef
.isUnevaluatedContext()) &&
19784 "missing non-odr-use marking for unevaluated decl ref");
19787 case OdrUseContext::FormallyOdrUsed
:
19788 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
19792 case OdrUseContext::Used
:
19793 // If we might later find that this expression isn't actually an odr-use,
19794 // delay the marking.
19795 if (E
&& Var
->isUsableInConstantExpressions(SemaRef
.Context
))
19796 SemaRef
.MaybeODRUseExprs
.insert(E
);
19798 MarkVarDeclODRUsed(Var
, Loc
, SemaRef
);
19801 case OdrUseContext::Dependent
:
19802 // If this is a dependent context, we don't need to mark variables as
19803 // odr-used, but we may still need to track them for lambda capture.
19804 // FIXME: Do we also need to do this inside dependent typeid expressions
19805 // (which are modeled as unevaluated at this point)?
19806 DoMarkPotentialCapture(SemaRef
, Loc
, Var
, E
);
19811 static void DoMarkBindingDeclReferenced(Sema
&SemaRef
, SourceLocation Loc
,
19812 BindingDecl
*BD
, Expr
*E
) {
19813 BD
->setReferenced();
19815 if (BD
->isInvalidDecl())
19818 OdrUseContext OdrUse
= isOdrUseContext(SemaRef
);
19819 if (OdrUse
== OdrUseContext::Used
) {
19820 QualType CaptureType
, DeclRefType
;
19821 SemaRef
.tryCaptureVariable(BD
, Loc
, Sema::TryCapture_Implicit
,
19822 /*EllipsisLoc*/ SourceLocation(),
19823 /*BuildAndDiagnose*/ true, CaptureType
,
19825 /*FunctionScopeIndexToStopAt*/ nullptr);
19826 } else if (OdrUse
== OdrUseContext::Dependent
) {
19827 DoMarkPotentialCapture(SemaRef
, Loc
, BD
, E
);
19831 void Sema::MarkVariableReferenced(SourceLocation Loc
, VarDecl
*Var
) {
19832 DoMarkVarDeclReferenced(*this, Loc
, Var
, nullptr, RefsMinusAssignments
);
19835 // C++ [temp.dep.expr]p3:
19836 // An id-expression is type-dependent if it contains:
19837 // - an identifier associated by name lookup with an entity captured by copy
19838 // in a lambda-expression that has an explicit object parameter whose type
19839 // is dependent ([dcl.fct]),
19840 static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(
19841 Sema
&SemaRef
, ValueDecl
*D
, Expr
*E
) {
19842 auto *ID
= dyn_cast
<DeclRefExpr
>(E
);
19843 if (!ID
|| ID
->isTypeDependent() || !ID
->refersToEnclosingVariableOrCapture())
19846 // If any enclosing lambda with a dependent explicit object parameter either
19847 // explicitly captures the variable by value, or has a capture default of '='
19848 // and does not capture the variable by reference, then the type of the DRE
19849 // is dependent on the type of that lambda's explicit object parameter.
19850 auto IsDependent
= [&]() {
19851 for (auto *Scope
: llvm::reverse(SemaRef
.FunctionScopes
)) {
19852 auto *LSI
= dyn_cast
<sema::LambdaScopeInfo
>(Scope
);
19856 if (LSI
->Lambda
&& !LSI
->Lambda
->Encloses(SemaRef
.CurContext
) &&
19857 LSI
->AfterParameterList
)
19860 const auto *MD
= LSI
->CallOperator
;
19861 if (MD
->getType().isNull())
19864 const auto *Ty
= MD
->getType()->getAs
<FunctionProtoType
>();
19865 if (!Ty
|| !MD
->isExplicitObjectMemberFunction() ||
19866 !Ty
->getParamType(0)->isDependentType())
19869 if (auto *C
= LSI
->CaptureMap
.count(D
) ? &LSI
->getCapture(D
) : nullptr) {
19870 if (C
->isCopyCapture())
19875 if (LSI
->ImpCaptureStyle
== LambdaScopeInfo::ImpCap_LambdaByval
)
19881 ID
->setCapturedByCopyInLambdaWithExplicitObjectParameter(
19882 IsDependent
, SemaRef
.getASTContext());
19886 MarkExprReferenced(Sema
&SemaRef
, SourceLocation Loc
, Decl
*D
, Expr
*E
,
19887 bool MightBeOdrUse
,
19888 llvm::DenseMap
<const VarDecl
*, int> &RefsMinusAssignments
) {
19889 if (SemaRef
.OpenMP().isInOpenMPDeclareTargetContext())
19890 SemaRef
.OpenMP().checkDeclIsAllowedInOpenMPTarget(E
, D
);
19892 if (VarDecl
*Var
= dyn_cast
<VarDecl
>(D
)) {
19893 DoMarkVarDeclReferenced(SemaRef
, Loc
, Var
, E
, RefsMinusAssignments
);
19894 if (SemaRef
.getLangOpts().CPlusPlus
)
19895 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef
,
19900 if (BindingDecl
*Decl
= dyn_cast
<BindingDecl
>(D
)) {
19901 DoMarkBindingDeclReferenced(SemaRef
, Loc
, Decl
, E
);
19902 if (SemaRef
.getLangOpts().CPlusPlus
)
19903 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef
,
19907 SemaRef
.MarkAnyDeclReferenced(Loc
, D
, MightBeOdrUse
);
19909 // If this is a call to a method via a cast, also mark the method in the
19910 // derived class used in case codegen can devirtualize the call.
19911 const MemberExpr
*ME
= dyn_cast
<MemberExpr
>(E
);
19914 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(ME
->getMemberDecl());
19917 // Only attempt to devirtualize if this is truly a virtual call.
19918 bool IsVirtualCall
= MD
->isVirtual() &&
19919 ME
->performsVirtualDispatch(SemaRef
.getLangOpts());
19920 if (!IsVirtualCall
)
19923 // If it's possible to devirtualize the call, mark the called function
19925 CXXMethodDecl
*DM
= MD
->getDevirtualizedMethod(
19926 ME
->getBase(), SemaRef
.getLangOpts().AppleKext
);
19928 SemaRef
.MarkAnyDeclReferenced(Loc
, DM
, MightBeOdrUse
);
19931 void Sema::MarkDeclRefReferenced(DeclRefExpr
*E
, const Expr
*Base
) {
19932 // TODO: update this with DR# once a defect report is filed.
19933 // C++11 defect. The address of a pure member should not be an ODR use, even
19934 // if it's a qualified reference.
19935 bool OdrUse
= true;
19936 if (const CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(E
->getDecl()))
19937 if (Method
->isVirtual() &&
19938 !Method
->getDevirtualizedMethod(Base
, getLangOpts().AppleKext
))
19941 if (auto *FD
= dyn_cast
<FunctionDecl
>(E
->getDecl())) {
19942 if (!isUnevaluatedContext() && !isConstantEvaluatedContext() &&
19943 !isImmediateFunctionContext() &&
19944 !isCheckingDefaultArgumentOrInitializer() &&
19945 FD
->isImmediateFunction() && !RebuildingImmediateInvocation
&&
19946 !FD
->isDependentContext())
19947 ExprEvalContexts
.back().ReferenceToConsteval
.insert(E
);
19949 MarkExprReferenced(*this, E
->getLocation(), E
->getDecl(), E
, OdrUse
,
19950 RefsMinusAssignments
);
19953 void Sema::MarkMemberReferenced(MemberExpr
*E
) {
19954 // C++11 [basic.def.odr]p2:
19955 // A non-overloaded function whose name appears as a potentially-evaluated
19956 // expression or a member of a set of candidate functions, if selected by
19957 // overload resolution when referred to from a potentially-evaluated
19958 // expression, is odr-used, unless it is a pure virtual function and its
19959 // name is not explicitly qualified.
19960 bool MightBeOdrUse
= true;
19961 if (E
->performsVirtualDispatch(getLangOpts())) {
19962 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(E
->getMemberDecl()))
19963 if (Method
->isPureVirtual())
19964 MightBeOdrUse
= false;
19966 SourceLocation Loc
=
19967 E
->getMemberLoc().isValid() ? E
->getMemberLoc() : E
->getBeginLoc();
19968 MarkExprReferenced(*this, Loc
, E
->getMemberDecl(), E
, MightBeOdrUse
,
19969 RefsMinusAssignments
);
19972 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr
*E
) {
19973 for (VarDecl
*VD
: *E
)
19974 MarkExprReferenced(*this, E
->getParameterPackLocation(), VD
, E
, true,
19975 RefsMinusAssignments
);
19978 /// Perform marking for a reference to an arbitrary declaration. It
19979 /// marks the declaration referenced, and performs odr-use checking for
19980 /// functions and variables. This method should not be used when building a
19981 /// normal expression which refers to a variable.
19982 void Sema::MarkAnyDeclReferenced(SourceLocation Loc
, Decl
*D
,
19983 bool MightBeOdrUse
) {
19984 if (MightBeOdrUse
) {
19985 if (auto *VD
= dyn_cast
<VarDecl
>(D
)) {
19986 MarkVariableReferenced(Loc
, VD
);
19990 if (auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
19991 MarkFunctionReferenced(Loc
, FD
, MightBeOdrUse
);
19994 D
->setReferenced();
19998 // Mark all of the declarations used by a type as referenced.
19999 // FIXME: Not fully implemented yet! We need to have a better understanding
20000 // of when we're entering a context we should not recurse into.
20001 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20002 // TreeTransforms rebuilding the type in a new context. Rather than
20003 // duplicating the TreeTransform logic, we should consider reusing it here.
20004 // Currently that causes problems when rebuilding LambdaExprs.
20005 class MarkReferencedDecls
: public DynamicRecursiveASTVisitor
{
20007 SourceLocation Loc
;
20010 MarkReferencedDecls(Sema
&S
, SourceLocation Loc
) : S(S
), Loc(Loc
) {}
20012 bool TraverseTemplateArgument(const TemplateArgument
&Arg
) override
;
20016 bool MarkReferencedDecls::TraverseTemplateArgument(
20017 const TemplateArgument
&Arg
) {
20019 // A non-type template argument is a constant-evaluated context.
20020 EnterExpressionEvaluationContext
Evaluated(
20021 S
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
20022 if (Arg
.getKind() == TemplateArgument::Declaration
) {
20023 if (Decl
*D
= Arg
.getAsDecl())
20024 S
.MarkAnyDeclReferenced(Loc
, D
, true);
20025 } else if (Arg
.getKind() == TemplateArgument::Expression
) {
20026 S
.MarkDeclarationsReferencedInExpr(Arg
.getAsExpr(), false);
20030 return DynamicRecursiveASTVisitor::TraverseTemplateArgument(Arg
);
20033 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc
, QualType T
) {
20034 MarkReferencedDecls
Marker(*this, Loc
);
20035 Marker
.TraverseType(T
);
20039 /// Helper class that marks all of the declarations referenced by
20040 /// potentially-evaluated subexpressions as "referenced".
20041 class EvaluatedExprMarker
: public UsedDeclVisitor
<EvaluatedExprMarker
> {
20043 typedef UsedDeclVisitor
<EvaluatedExprMarker
> Inherited
;
20044 bool SkipLocalVariables
;
20045 ArrayRef
<const Expr
*> StopAt
;
20047 EvaluatedExprMarker(Sema
&S
, bool SkipLocalVariables
,
20048 ArrayRef
<const Expr
*> StopAt
)
20049 : Inherited(S
), SkipLocalVariables(SkipLocalVariables
), StopAt(StopAt
) {}
20051 void visitUsedDecl(SourceLocation Loc
, Decl
*D
) {
20052 S
.MarkFunctionReferenced(Loc
, cast
<FunctionDecl
>(D
));
20055 void Visit(Expr
*E
) {
20056 if (llvm::is_contained(StopAt
, E
))
20058 Inherited::Visit(E
);
20061 void VisitConstantExpr(ConstantExpr
*E
) {
20062 // Don't mark declarations within a ConstantExpression, as this expression
20063 // will be evaluated and folded to a value.
20066 void VisitDeclRefExpr(DeclRefExpr
*E
) {
20067 // If we were asked not to visit local variables, don't.
20068 if (SkipLocalVariables
) {
20069 if (VarDecl
*VD
= dyn_cast
<VarDecl
>(E
->getDecl()))
20070 if (VD
->hasLocalStorage())
20074 // FIXME: This can trigger the instantiation of the initializer of a
20075 // variable, which can cause the expression to become value-dependent
20076 // or error-dependent. Do we need to propagate the new dependence bits?
20077 S
.MarkDeclRefReferenced(E
);
20080 void VisitMemberExpr(MemberExpr
*E
) {
20081 S
.MarkMemberReferenced(E
);
20082 Visit(E
->getBase());
20087 void Sema::MarkDeclarationsReferencedInExpr(Expr
*E
,
20088 bool SkipLocalVariables
,
20089 ArrayRef
<const Expr
*> StopAt
) {
20090 EvaluatedExprMarker(*this, SkipLocalVariables
, StopAt
).Visit(E
);
20093 /// Emit a diagnostic when statements are reachable.
20094 /// FIXME: check for reachability even in expressions for which we don't build a
20095 /// CFG (eg, in the initializer of a global or in a constant expression).
20097 /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
20098 bool Sema::DiagIfReachable(SourceLocation Loc
, ArrayRef
<const Stmt
*> Stmts
,
20099 const PartialDiagnostic
&PD
) {
20100 if (!Stmts
.empty() && getCurFunctionOrMethodDecl()) {
20101 if (!FunctionScopes
.empty())
20102 FunctionScopes
.back()->PossiblyUnreachableDiags
.push_back(
20103 sema::PossiblyUnreachableDiag(PD
, Loc
, Stmts
));
20107 // The initializer of a constexpr variable or of the first declaration of a
20108 // static data member is not syntactically a constant evaluated constant,
20109 // but nonetheless is always required to be a constant expression, so we
20110 // can skip diagnosing.
20111 // FIXME: Using the mangling context here is a hack.
20112 if (auto *VD
= dyn_cast_or_null
<VarDecl
>(
20113 ExprEvalContexts
.back().ManglingContextDecl
)) {
20114 if (VD
->isConstexpr() ||
20115 (VD
->isStaticDataMember() && VD
->isFirstDecl() && !VD
->isInline()))
20117 // FIXME: For any other kind of variable, we should build a CFG for its
20118 // initializer and check whether the context in question is reachable.
20125 /// Emit a diagnostic that describes an effect on the run-time behavior
20126 /// of the program being compiled.
20128 /// This routine emits the given diagnostic when the code currently being
20129 /// type-checked is "potentially evaluated", meaning that there is a
20130 /// possibility that the code will actually be executable. Code in sizeof()
20131 /// expressions, code used only during overload resolution, etc., are not
20132 /// potentially evaluated. This routine will suppress such diagnostics or,
20133 /// in the absolutely nutty case of potentially potentially evaluated
20134 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
20137 /// This routine should be used for all diagnostics that describe the run-time
20138 /// behavior of a program, such as passing a non-POD value through an ellipsis.
20139 /// Failure to do so will likely result in spurious diagnostics or failures
20140 /// during overload resolution or within sizeof/alignof/typeof/typeid.
20141 bool Sema::DiagRuntimeBehavior(SourceLocation Loc
, ArrayRef
<const Stmt
*> Stmts
,
20142 const PartialDiagnostic
&PD
) {
20144 if (ExprEvalContexts
.back().isDiscardedStatementContext())
20147 switch (ExprEvalContexts
.back().Context
) {
20148 case ExpressionEvaluationContext::Unevaluated
:
20149 case ExpressionEvaluationContext::UnevaluatedList
:
20150 case ExpressionEvaluationContext::UnevaluatedAbstract
:
20151 case ExpressionEvaluationContext::DiscardedStatement
:
20152 // The argument will never be evaluated, so don't complain.
20155 case ExpressionEvaluationContext::ConstantEvaluated
:
20156 case ExpressionEvaluationContext::ImmediateFunctionContext
:
20157 // Relevant diagnostics should be produced by constant evaluation.
20160 case ExpressionEvaluationContext::PotentiallyEvaluated
:
20161 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed
:
20162 return DiagIfReachable(Loc
, Stmts
, PD
);
20168 bool Sema::DiagRuntimeBehavior(SourceLocation Loc
, const Stmt
*Statement
,
20169 const PartialDiagnostic
&PD
) {
20170 return DiagRuntimeBehavior(
20171 Loc
, Statement
? llvm::ArrayRef(Statement
) : llvm::ArrayRef
<Stmt
*>(),
20175 bool Sema::CheckCallReturnType(QualType ReturnType
, SourceLocation Loc
,
20176 CallExpr
*CE
, FunctionDecl
*FD
) {
20177 if (ReturnType
->isVoidType() || !ReturnType
->isIncompleteType())
20180 // If we're inside a decltype's expression, don't check for a valid return
20181 // type or construct temporaries until we know whether this is the last call.
20182 if (ExprEvalContexts
.back().ExprContext
==
20183 ExpressionEvaluationContextRecord::EK_Decltype
) {
20184 ExprEvalContexts
.back().DelayedDecltypeCalls
.push_back(CE
);
20188 class CallReturnIncompleteDiagnoser
: public TypeDiagnoser
{
20193 CallReturnIncompleteDiagnoser(FunctionDecl
*FD
, CallExpr
*CE
)
20194 : FD(FD
), CE(CE
) { }
20196 void diagnose(Sema
&S
, SourceLocation Loc
, QualType T
) override
{
20198 S
.Diag(Loc
, diag::err_call_incomplete_return
)
20199 << T
<< CE
->getSourceRange();
20203 S
.Diag(Loc
, diag::err_call_function_incomplete_return
)
20204 << CE
->getSourceRange() << FD
<< T
;
20205 S
.Diag(FD
->getLocation(), diag::note_entity_declared_at
)
20206 << FD
->getDeclName();
20208 } Diagnoser(FD
, CE
);
20210 if (RequireCompleteType(Loc
, ReturnType
, Diagnoser
))
20216 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
20217 // will prevent this condition from triggering, which is what we want.
20218 void Sema::DiagnoseAssignmentAsCondition(Expr
*E
) {
20219 SourceLocation Loc
;
20221 unsigned diagnostic
= diag::warn_condition_is_assignment
;
20222 bool IsOrAssign
= false;
20224 if (BinaryOperator
*Op
= dyn_cast
<BinaryOperator
>(E
)) {
20225 if (Op
->getOpcode() != BO_Assign
&& Op
->getOpcode() != BO_OrAssign
)
20228 IsOrAssign
= Op
->getOpcode() == BO_OrAssign
;
20230 // Greylist some idioms by putting them into a warning subcategory.
20231 if (ObjCMessageExpr
*ME
20232 = dyn_cast
<ObjCMessageExpr
>(Op
->getRHS()->IgnoreParenCasts())) {
20233 Selector Sel
= ME
->getSelector();
20235 // self = [<foo> init...]
20236 if (ObjC().isSelfExpr(Op
->getLHS()) && ME
->getMethodFamily() == OMF_init
)
20237 diagnostic
= diag::warn_condition_is_idiomatic_assignment
;
20239 // <foo> = [<bar> nextObject]
20240 else if (Sel
.isUnarySelector() && Sel
.getNameForSlot(0) == "nextObject")
20241 diagnostic
= diag::warn_condition_is_idiomatic_assignment
;
20244 Loc
= Op
->getOperatorLoc();
20245 } else if (CXXOperatorCallExpr
*Op
= dyn_cast
<CXXOperatorCallExpr
>(E
)) {
20246 if (Op
->getOperator() != OO_Equal
&& Op
->getOperator() != OO_PipeEqual
)
20249 IsOrAssign
= Op
->getOperator() == OO_PipeEqual
;
20250 Loc
= Op
->getOperatorLoc();
20251 } else if (PseudoObjectExpr
*POE
= dyn_cast
<PseudoObjectExpr
>(E
))
20252 return DiagnoseAssignmentAsCondition(POE
->getSyntacticForm());
20254 // Not an assignment.
20258 Diag(Loc
, diagnostic
) << E
->getSourceRange();
20260 SourceLocation Open
= E
->getBeginLoc();
20261 SourceLocation Close
= getLocForEndOfToken(E
->getSourceRange().getEnd());
20262 Diag(Loc
, diag::note_condition_assign_silence
)
20263 << FixItHint::CreateInsertion(Open
, "(")
20264 << FixItHint::CreateInsertion(Close
, ")");
20267 Diag(Loc
, diag::note_condition_or_assign_to_comparison
)
20268 << FixItHint::CreateReplacement(Loc
, "!=");
20270 Diag(Loc
, diag::note_condition_assign_to_comparison
)
20271 << FixItHint::CreateReplacement(Loc
, "==");
20274 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr
*ParenE
) {
20275 // Don't warn if the parens came from a macro.
20276 SourceLocation parenLoc
= ParenE
->getBeginLoc();
20277 if (parenLoc
.isInvalid() || parenLoc
.isMacroID())
20279 // Don't warn for dependent expressions.
20280 if (ParenE
->isTypeDependent())
20283 Expr
*E
= ParenE
->IgnoreParens();
20284 if (ParenE
->isProducedByFoldExpansion() && ParenE
->getSubExpr() == E
)
20287 if (BinaryOperator
*opE
= dyn_cast
<BinaryOperator
>(E
))
20288 if (opE
->getOpcode() == BO_EQ
&&
20289 opE
->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context
)
20290 == Expr::MLV_Valid
) {
20291 SourceLocation Loc
= opE
->getOperatorLoc();
20293 Diag(Loc
, diag::warn_equality_with_extra_parens
) << E
->getSourceRange();
20294 SourceRange ParenERange
= ParenE
->getSourceRange();
20295 Diag(Loc
, diag::note_equality_comparison_silence
)
20296 << FixItHint::CreateRemoval(ParenERange
.getBegin())
20297 << FixItHint::CreateRemoval(ParenERange
.getEnd());
20298 Diag(Loc
, diag::note_equality_comparison_to_assign
)
20299 << FixItHint::CreateReplacement(Loc
, "=");
20303 ExprResult
Sema::CheckBooleanCondition(SourceLocation Loc
, Expr
*E
,
20304 bool IsConstexpr
) {
20305 DiagnoseAssignmentAsCondition(E
);
20306 if (ParenExpr
*parenE
= dyn_cast
<ParenExpr
>(E
))
20307 DiagnoseEqualityWithExtraParens(parenE
);
20309 ExprResult result
= CheckPlaceholderExpr(E
);
20310 if (result
.isInvalid()) return ExprError();
20313 if (!E
->isTypeDependent()) {
20314 if (getLangOpts().CPlusPlus
)
20315 return CheckCXXBooleanCondition(E
, IsConstexpr
); // C++ 6.4p4
20317 ExprResult ERes
= DefaultFunctionArrayLvalueConversion(E
);
20318 if (ERes
.isInvalid())
20319 return ExprError();
20322 QualType T
= E
->getType();
20323 if (!T
->isScalarType()) { // C99 6.8.4.1p1
20324 Diag(Loc
, diag::err_typecheck_statement_requires_scalar
)
20325 << T
<< E
->getSourceRange();
20326 return ExprError();
20328 CheckBoolLikeConversion(E
, Loc
);
20334 Sema::ConditionResult
Sema::ActOnCondition(Scope
*S
, SourceLocation Loc
,
20335 Expr
*SubExpr
, ConditionKind CK
,
20337 // MissingOK indicates whether having no condition expression is valid
20338 // (for loop) or invalid (e.g. while loop).
20340 return MissingOK
? ConditionResult() : ConditionError();
20344 case ConditionKind::Boolean
:
20345 Cond
= CheckBooleanCondition(Loc
, SubExpr
);
20348 case ConditionKind::ConstexprIf
:
20349 Cond
= CheckBooleanCondition(Loc
, SubExpr
, true);
20352 case ConditionKind::Switch
:
20353 Cond
= CheckSwitchCondition(Loc
, SubExpr
);
20356 if (Cond
.isInvalid()) {
20357 Cond
= CreateRecoveryExpr(SubExpr
->getBeginLoc(), SubExpr
->getEndLoc(),
20358 {SubExpr
}, PreferredConditionType(CK
));
20360 return ConditionError();
20362 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
20363 FullExprArg FullExpr
= MakeFullExpr(Cond
.get(), Loc
);
20364 if (!FullExpr
.get())
20365 return ConditionError();
20367 return ConditionResult(*this, nullptr, FullExpr
,
20368 CK
== ConditionKind::ConstexprIf
);
20372 /// A visitor for rebuilding a call to an __unknown_any expression
20373 /// to have an appropriate type.
20374 struct RebuildUnknownAnyFunction
20375 : StmtVisitor
<RebuildUnknownAnyFunction
, ExprResult
> {
20379 RebuildUnknownAnyFunction(Sema
&S
) : S(S
) {}
20381 ExprResult
VisitStmt(Stmt
*S
) {
20382 llvm_unreachable("unexpected statement!");
20385 ExprResult
VisitExpr(Expr
*E
) {
20386 S
.Diag(E
->getExprLoc(), diag::err_unsupported_unknown_any_call
)
20387 << E
->getSourceRange();
20388 return ExprError();
20391 /// Rebuild an expression which simply semantically wraps another
20392 /// expression which it shares the type and value kind of.
20393 template <class T
> ExprResult
rebuildSugarExpr(T
*E
) {
20394 ExprResult SubResult
= Visit(E
->getSubExpr());
20395 if (SubResult
.isInvalid()) return ExprError();
20397 Expr
*SubExpr
= SubResult
.get();
20398 E
->setSubExpr(SubExpr
);
20399 E
->setType(SubExpr
->getType());
20400 E
->setValueKind(SubExpr
->getValueKind());
20401 assert(E
->getObjectKind() == OK_Ordinary
);
20405 ExprResult
VisitParenExpr(ParenExpr
*E
) {
20406 return rebuildSugarExpr(E
);
20409 ExprResult
VisitUnaryExtension(UnaryOperator
*E
) {
20410 return rebuildSugarExpr(E
);
20413 ExprResult
VisitUnaryAddrOf(UnaryOperator
*E
) {
20414 ExprResult SubResult
= Visit(E
->getSubExpr());
20415 if (SubResult
.isInvalid()) return ExprError();
20417 Expr
*SubExpr
= SubResult
.get();
20418 E
->setSubExpr(SubExpr
);
20419 E
->setType(S
.Context
.getPointerType(SubExpr
->getType()));
20420 assert(E
->isPRValue());
20421 assert(E
->getObjectKind() == OK_Ordinary
);
20425 ExprResult
resolveDecl(Expr
*E
, ValueDecl
*VD
) {
20426 if (!isa
<FunctionDecl
>(VD
)) return VisitExpr(E
);
20428 E
->setType(VD
->getType());
20430 assert(E
->isPRValue());
20431 if (S
.getLangOpts().CPlusPlus
&&
20432 !(isa
<CXXMethodDecl
>(VD
) &&
20433 cast
<CXXMethodDecl
>(VD
)->isInstance()))
20434 E
->setValueKind(VK_LValue
);
20439 ExprResult
VisitMemberExpr(MemberExpr
*E
) {
20440 return resolveDecl(E
, E
->getMemberDecl());
20443 ExprResult
VisitDeclRefExpr(DeclRefExpr
*E
) {
20444 return resolveDecl(E
, E
->getDecl());
20449 /// Given a function expression of unknown-any type, try to rebuild it
20450 /// to have a function type.
20451 static ExprResult
rebuildUnknownAnyFunction(Sema
&S
, Expr
*FunctionExpr
) {
20452 ExprResult Result
= RebuildUnknownAnyFunction(S
).Visit(FunctionExpr
);
20453 if (Result
.isInvalid()) return ExprError();
20454 return S
.DefaultFunctionArrayConversion(Result
.get());
20458 /// A visitor for rebuilding an expression of type __unknown_anytype
20459 /// into one which resolves the type directly on the referring
20460 /// expression. Strict preservation of the original source
20461 /// structure is not a goal.
20462 struct RebuildUnknownAnyExpr
20463 : StmtVisitor
<RebuildUnknownAnyExpr
, ExprResult
> {
20467 /// The current destination type.
20470 RebuildUnknownAnyExpr(Sema
&S
, QualType CastType
)
20471 : S(S
), DestType(CastType
) {}
20473 ExprResult
VisitStmt(Stmt
*S
) {
20474 llvm_unreachable("unexpected statement!");
20477 ExprResult
VisitExpr(Expr
*E
) {
20478 S
.Diag(E
->getExprLoc(), diag::err_unsupported_unknown_any_expr
)
20479 << E
->getSourceRange();
20480 return ExprError();
20483 ExprResult
VisitCallExpr(CallExpr
*E
);
20484 ExprResult
VisitObjCMessageExpr(ObjCMessageExpr
*E
);
20486 /// Rebuild an expression which simply semantically wraps another
20487 /// expression which it shares the type and value kind of.
20488 template <class T
> ExprResult
rebuildSugarExpr(T
*E
) {
20489 ExprResult SubResult
= Visit(E
->getSubExpr());
20490 if (SubResult
.isInvalid()) return ExprError();
20491 Expr
*SubExpr
= SubResult
.get();
20492 E
->setSubExpr(SubExpr
);
20493 E
->setType(SubExpr
->getType());
20494 E
->setValueKind(SubExpr
->getValueKind());
20495 assert(E
->getObjectKind() == OK_Ordinary
);
20499 ExprResult
VisitParenExpr(ParenExpr
*E
) {
20500 return rebuildSugarExpr(E
);
20503 ExprResult
VisitUnaryExtension(UnaryOperator
*E
) {
20504 return rebuildSugarExpr(E
);
20507 ExprResult
VisitUnaryAddrOf(UnaryOperator
*E
) {
20508 const PointerType
*Ptr
= DestType
->getAs
<PointerType
>();
20510 S
.Diag(E
->getOperatorLoc(), diag::err_unknown_any_addrof
)
20511 << E
->getSourceRange();
20512 return ExprError();
20515 if (isa
<CallExpr
>(E
->getSubExpr())) {
20516 S
.Diag(E
->getOperatorLoc(), diag::err_unknown_any_addrof_call
)
20517 << E
->getSourceRange();
20518 return ExprError();
20521 assert(E
->isPRValue());
20522 assert(E
->getObjectKind() == OK_Ordinary
);
20523 E
->setType(DestType
);
20525 // Build the sub-expression as if it were an object of the pointee type.
20526 DestType
= Ptr
->getPointeeType();
20527 ExprResult SubResult
= Visit(E
->getSubExpr());
20528 if (SubResult
.isInvalid()) return ExprError();
20529 E
->setSubExpr(SubResult
.get());
20533 ExprResult
VisitImplicitCastExpr(ImplicitCastExpr
*E
);
20535 ExprResult
resolveDecl(Expr
*E
, ValueDecl
*VD
);
20537 ExprResult
VisitMemberExpr(MemberExpr
*E
) {
20538 return resolveDecl(E
, E
->getMemberDecl());
20541 ExprResult
VisitDeclRefExpr(DeclRefExpr
*E
) {
20542 return resolveDecl(E
, E
->getDecl());
20547 /// Rebuilds a call expression which yielded __unknown_anytype.
20548 ExprResult
RebuildUnknownAnyExpr::VisitCallExpr(CallExpr
*E
) {
20549 Expr
*CalleeExpr
= E
->getCallee();
20553 FK_FunctionPointer
,
20558 QualType CalleeType
= CalleeExpr
->getType();
20559 if (CalleeType
== S
.Context
.BoundMemberTy
) {
20560 assert(isa
<CXXMemberCallExpr
>(E
) || isa
<CXXOperatorCallExpr
>(E
));
20561 Kind
= FK_MemberFunction
;
20562 CalleeType
= Expr::findBoundMemberType(CalleeExpr
);
20563 } else if (const PointerType
*Ptr
= CalleeType
->getAs
<PointerType
>()) {
20564 CalleeType
= Ptr
->getPointeeType();
20565 Kind
= FK_FunctionPointer
;
20567 CalleeType
= CalleeType
->castAs
<BlockPointerType
>()->getPointeeType();
20568 Kind
= FK_BlockPointer
;
20570 const FunctionType
*FnType
= CalleeType
->castAs
<FunctionType
>();
20572 // Verify that this is a legal result type of a function.
20573 if (DestType
->isArrayType() || DestType
->isFunctionType()) {
20574 unsigned diagID
= diag::err_func_returning_array_function
;
20575 if (Kind
== FK_BlockPointer
)
20576 diagID
= diag::err_block_returning_array_function
;
20578 S
.Diag(E
->getExprLoc(), diagID
)
20579 << DestType
->isFunctionType() << DestType
;
20580 return ExprError();
20583 // Otherwise, go ahead and set DestType as the call's result.
20584 E
->setType(DestType
.getNonLValueExprType(S
.Context
));
20585 E
->setValueKind(Expr::getValueKindForType(DestType
));
20586 assert(E
->getObjectKind() == OK_Ordinary
);
20588 // Rebuild the function type, replacing the result type with DestType.
20589 const FunctionProtoType
*Proto
= dyn_cast
<FunctionProtoType
>(FnType
);
20591 // __unknown_anytype(...) is a special case used by the debugger when
20592 // it has no idea what a function's signature is.
20594 // We want to build this call essentially under the K&R
20595 // unprototyped rules, but making a FunctionNoProtoType in C++
20596 // would foul up all sorts of assumptions. However, we cannot
20597 // simply pass all arguments as variadic arguments, nor can we
20598 // portably just call the function under a non-variadic type; see
20599 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
20600 // However, it turns out that in practice it is generally safe to
20601 // call a function declared as "A foo(B,C,D);" under the prototype
20602 // "A foo(B,C,D,...);". The only known exception is with the
20603 // Windows ABI, where any variadic function is implicitly cdecl
20604 // regardless of its normal CC. Therefore we change the parameter
20605 // types to match the types of the arguments.
20607 // This is a hack, but it is far superior to moving the
20608 // corresponding target-specific code from IR-gen to Sema/AST.
20610 ArrayRef
<QualType
> ParamTypes
= Proto
->getParamTypes();
20611 SmallVector
<QualType
, 8> ArgTypes
;
20612 if (ParamTypes
.empty() && Proto
->isVariadic()) { // the special case
20613 ArgTypes
.reserve(E
->getNumArgs());
20614 for (unsigned i
= 0, e
= E
->getNumArgs(); i
!= e
; ++i
) {
20615 ArgTypes
.push_back(S
.Context
.getReferenceQualifiedType(E
->getArg(i
)));
20617 ParamTypes
= ArgTypes
;
20619 DestType
= S
.Context
.getFunctionType(DestType
, ParamTypes
,
20620 Proto
->getExtProtoInfo());
20622 DestType
= S
.Context
.getFunctionNoProtoType(DestType
,
20623 FnType
->getExtInfo());
20626 // Rebuild the appropriate pointer-to-function type.
20628 case FK_MemberFunction
:
20632 case FK_FunctionPointer
:
20633 DestType
= S
.Context
.getPointerType(DestType
);
20636 case FK_BlockPointer
:
20637 DestType
= S
.Context
.getBlockPointerType(DestType
);
20641 // Finally, we can recurse.
20642 ExprResult CalleeResult
= Visit(CalleeExpr
);
20643 if (!CalleeResult
.isUsable()) return ExprError();
20644 E
->setCallee(CalleeResult
.get());
20646 // Bind a temporary if necessary.
20647 return S
.MaybeBindToTemporary(E
);
20650 ExprResult
RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr
*E
) {
20651 // Verify that this is a legal result type of a call.
20652 if (DestType
->isArrayType() || DestType
->isFunctionType()) {
20653 S
.Diag(E
->getExprLoc(), diag::err_func_returning_array_function
)
20654 << DestType
->isFunctionType() << DestType
;
20655 return ExprError();
20658 // Rewrite the method result type if available.
20659 if (ObjCMethodDecl
*Method
= E
->getMethodDecl()) {
20660 assert(Method
->getReturnType() == S
.Context
.UnknownAnyTy
);
20661 Method
->setReturnType(DestType
);
20664 // Change the type of the message.
20665 E
->setType(DestType
.getNonReferenceType());
20666 E
->setValueKind(Expr::getValueKindForType(DestType
));
20668 return S
.MaybeBindToTemporary(E
);
20671 ExprResult
RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr
*E
) {
20672 // The only case we should ever see here is a function-to-pointer decay.
20673 if (E
->getCastKind() == CK_FunctionToPointerDecay
) {
20674 assert(E
->isPRValue());
20675 assert(E
->getObjectKind() == OK_Ordinary
);
20677 E
->setType(DestType
);
20679 // Rebuild the sub-expression as the pointee (function) type.
20680 DestType
= DestType
->castAs
<PointerType
>()->getPointeeType();
20682 ExprResult Result
= Visit(E
->getSubExpr());
20683 if (!Result
.isUsable()) return ExprError();
20685 E
->setSubExpr(Result
.get());
20687 } else if (E
->getCastKind() == CK_LValueToRValue
) {
20688 assert(E
->isPRValue());
20689 assert(E
->getObjectKind() == OK_Ordinary
);
20691 assert(isa
<BlockPointerType
>(E
->getType()));
20693 E
->setType(DestType
);
20695 // The sub-expression has to be a lvalue reference, so rebuild it as such.
20696 DestType
= S
.Context
.getLValueReferenceType(DestType
);
20698 ExprResult Result
= Visit(E
->getSubExpr());
20699 if (!Result
.isUsable()) return ExprError();
20701 E
->setSubExpr(Result
.get());
20704 llvm_unreachable("Unhandled cast type!");
20708 ExprResult
RebuildUnknownAnyExpr::resolveDecl(Expr
*E
, ValueDecl
*VD
) {
20709 ExprValueKind ValueKind
= VK_LValue
;
20710 QualType Type
= DestType
;
20712 // We know how to make this work for certain kinds of decls:
20715 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(VD
)) {
20716 if (const PointerType
*Ptr
= Type
->getAs
<PointerType
>()) {
20717 DestType
= Ptr
->getPointeeType();
20718 ExprResult Result
= resolveDecl(E
, VD
);
20719 if (Result
.isInvalid()) return ExprError();
20720 return S
.ImpCastExprToType(Result
.get(), Type
, CK_FunctionToPointerDecay
,
20724 if (!Type
->isFunctionType()) {
20725 S
.Diag(E
->getExprLoc(), diag::err_unknown_any_function
)
20726 << VD
<< E
->getSourceRange();
20727 return ExprError();
20729 if (const FunctionProtoType
*FT
= Type
->getAs
<FunctionProtoType
>()) {
20730 // We must match the FunctionDecl's type to the hack introduced in
20731 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
20732 // type. See the lengthy commentary in that routine.
20733 QualType FDT
= FD
->getType();
20734 const FunctionType
*FnType
= FDT
->castAs
<FunctionType
>();
20735 const FunctionProtoType
*Proto
= dyn_cast_or_null
<FunctionProtoType
>(FnType
);
20736 DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(E
);
20737 if (DRE
&& Proto
&& Proto
->getParamTypes().empty() && Proto
->isVariadic()) {
20738 SourceLocation Loc
= FD
->getLocation();
20739 FunctionDecl
*NewFD
= FunctionDecl::Create(
20740 S
.Context
, FD
->getDeclContext(), Loc
, Loc
,
20741 FD
->getNameInfo().getName(), DestType
, FD
->getTypeSourceInfo(),
20742 SC_None
, S
.getCurFPFeatures().isFPConstrained(),
20743 false /*isInlineSpecified*/, FD
->hasPrototype(),
20744 /*ConstexprKind*/ ConstexprSpecKind::Unspecified
);
20746 if (FD
->getQualifier())
20747 NewFD
->setQualifierInfo(FD
->getQualifierLoc());
20749 SmallVector
<ParmVarDecl
*, 16> Params
;
20750 for (const auto &AI
: FT
->param_types()) {
20751 ParmVarDecl
*Param
=
20752 S
.BuildParmVarDeclForTypedef(FD
, Loc
, AI
);
20753 Param
->setScopeInfo(0, Params
.size());
20754 Params
.push_back(Param
);
20756 NewFD
->setParams(Params
);
20757 DRE
->setDecl(NewFD
);
20758 VD
= DRE
->getDecl();
20762 if (CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(FD
))
20763 if (MD
->isInstance()) {
20764 ValueKind
= VK_PRValue
;
20765 Type
= S
.Context
.BoundMemberTy
;
20768 // Function references aren't l-values in C.
20769 if (!S
.getLangOpts().CPlusPlus
)
20770 ValueKind
= VK_PRValue
;
20773 } else if (isa
<VarDecl
>(VD
)) {
20774 if (const ReferenceType
*RefTy
= Type
->getAs
<ReferenceType
>()) {
20775 Type
= RefTy
->getPointeeType();
20776 } else if (Type
->isFunctionType()) {
20777 S
.Diag(E
->getExprLoc(), diag::err_unknown_any_var_function_type
)
20778 << VD
<< E
->getSourceRange();
20779 return ExprError();
20784 S
.Diag(E
->getExprLoc(), diag::err_unsupported_unknown_any_decl
)
20785 << VD
<< E
->getSourceRange();
20786 return ExprError();
20789 // Modifying the declaration like this is friendly to IR-gen but
20790 // also really dangerous.
20791 VD
->setType(DestType
);
20793 E
->setValueKind(ValueKind
);
20797 ExprResult
Sema::checkUnknownAnyCast(SourceRange TypeRange
, QualType CastType
,
20798 Expr
*CastExpr
, CastKind
&CastKind
,
20799 ExprValueKind
&VK
, CXXCastPath
&Path
) {
20800 // The type we're casting to must be either void or complete.
20801 if (!CastType
->isVoidType() &&
20802 RequireCompleteType(TypeRange
.getBegin(), CastType
,
20803 diag::err_typecheck_cast_to_incomplete
))
20804 return ExprError();
20806 // Rewrite the casted expression from scratch.
20807 ExprResult result
= RebuildUnknownAnyExpr(*this, CastType
).Visit(CastExpr
);
20808 if (!result
.isUsable()) return ExprError();
20810 CastExpr
= result
.get();
20811 VK
= CastExpr
->getValueKind();
20812 CastKind
= CK_NoOp
;
20817 ExprResult
Sema::forceUnknownAnyToType(Expr
*E
, QualType ToType
) {
20818 return RebuildUnknownAnyExpr(*this, ToType
).Visit(E
);
20821 ExprResult
Sema::checkUnknownAnyArg(SourceLocation callLoc
,
20822 Expr
*arg
, QualType
¶mType
) {
20823 // If the syntactic form of the argument is not an explicit cast of
20824 // any sort, just do default argument promotion.
20825 ExplicitCastExpr
*castArg
= dyn_cast
<ExplicitCastExpr
>(arg
->IgnoreParens());
20827 ExprResult result
= DefaultArgumentPromotion(arg
);
20828 if (result
.isInvalid()) return ExprError();
20829 paramType
= result
.get()->getType();
20833 // Otherwise, use the type that was written in the explicit cast.
20834 assert(!arg
->hasPlaceholderType());
20835 paramType
= castArg
->getTypeAsWritten();
20837 // Copy-initialize a parameter of that type.
20838 InitializedEntity entity
=
20839 InitializedEntity::InitializeParameter(Context
, paramType
,
20840 /*consumed*/ false);
20841 return PerformCopyInitialization(entity
, callLoc
, arg
);
20844 static ExprResult
diagnoseUnknownAnyExpr(Sema
&S
, Expr
*E
) {
20846 unsigned diagID
= diag::err_uncasted_use_of_unknown_any
;
20848 E
= E
->IgnoreParenImpCasts();
20849 if (CallExpr
*call
= dyn_cast
<CallExpr
>(E
)) {
20850 E
= call
->getCallee();
20851 diagID
= diag::err_uncasted_call_of_unknown_any
;
20857 SourceLocation loc
;
20859 if (DeclRefExpr
*ref
= dyn_cast
<DeclRefExpr
>(E
)) {
20860 loc
= ref
->getLocation();
20861 d
= ref
->getDecl();
20862 } else if (MemberExpr
*mem
= dyn_cast
<MemberExpr
>(E
)) {
20863 loc
= mem
->getMemberLoc();
20864 d
= mem
->getMemberDecl();
20865 } else if (ObjCMessageExpr
*msg
= dyn_cast
<ObjCMessageExpr
>(E
)) {
20866 diagID
= diag::err_uncasted_call_of_unknown_any
;
20867 loc
= msg
->getSelectorStartLoc();
20868 d
= msg
->getMethodDecl();
20870 S
.Diag(loc
, diag::err_uncasted_send_to_unknown_any_method
)
20871 << static_cast<unsigned>(msg
->isClassMessage()) << msg
->getSelector()
20872 << orig
->getSourceRange();
20873 return ExprError();
20876 S
.Diag(E
->getExprLoc(), diag::err_unsupported_unknown_any_expr
)
20877 << E
->getSourceRange();
20878 return ExprError();
20881 S
.Diag(loc
, diagID
) << d
<< orig
->getSourceRange();
20883 // Never recoverable.
20884 return ExprError();
20887 ExprResult
Sema::CheckPlaceholderExpr(Expr
*E
) {
20888 if (!Context
.isDependenceAllowed()) {
20889 // C cannot handle TypoExpr nodes on either side of a binop because it
20890 // doesn't handle dependent types properly, so make sure any TypoExprs have
20891 // been dealt with before checking the operands.
20892 ExprResult Result
= CorrectDelayedTyposInExpr(E
);
20893 if (!Result
.isUsable()) return ExprError();
20897 const BuiltinType
*placeholderType
= E
->getType()->getAsPlaceholderType();
20898 if (!placeholderType
) return E
;
20900 switch (placeholderType
->getKind()) {
20901 case BuiltinType::UnresolvedTemplate
: {
20902 auto *ULE
= cast
<UnresolvedLookupExpr
>(E
);
20903 const DeclarationNameInfo
&NameInfo
= ULE
->getNameInfo();
20904 // There's only one FoundDecl for UnresolvedTemplate type. See
20905 // BuildTemplateIdExpr.
20906 NamedDecl
*Temp
= *ULE
->decls_begin();
20907 const bool IsTypeAliasTemplateDecl
= isa
<TypeAliasTemplateDecl
>(Temp
);
20909 if (NestedNameSpecifierLoc Loc
= ULE
->getQualifierLoc(); Loc
.hasQualifier())
20910 Diag(NameInfo
.getLoc(), diag::err_template_kw_refers_to_type_template
)
20911 << Loc
.getNestedNameSpecifier() << NameInfo
.getName().getAsString()
20912 << Loc
.getSourceRange() << IsTypeAliasTemplateDecl
;
20914 Diag(NameInfo
.getLoc(), diag::err_template_kw_refers_to_type_template
)
20915 << "" << NameInfo
.getName().getAsString() << ULE
->getSourceRange()
20916 << IsTypeAliasTemplateDecl
;
20917 Diag(Temp
->getLocation(), diag::note_referenced_type_template
)
20918 << IsTypeAliasTemplateDecl
;
20920 return CreateRecoveryExpr(NameInfo
.getBeginLoc(), NameInfo
.getEndLoc(), {});
20923 // Overloaded expressions.
20924 case BuiltinType::Overload
: {
20925 // Try to resolve a single function template specialization.
20926 // This is obligatory.
20927 ExprResult Result
= E
;
20928 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result
, false))
20931 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
20932 // leaves Result unchanged on failure.
20934 if (resolveAndFixAddressOfSingleOverloadCandidate(Result
))
20937 // If that failed, try to recover with a call.
20938 tryToRecoverWithCall(Result
, PDiag(diag::err_ovl_unresolvable
),
20939 /*complain*/ true);
20943 // Bound member functions.
20944 case BuiltinType::BoundMember
: {
20945 ExprResult result
= E
;
20946 const Expr
*BME
= E
->IgnoreParens();
20947 PartialDiagnostic PD
= PDiag(diag::err_bound_member_function
);
20948 // Try to give a nicer diagnostic if it is a bound member that we recognize.
20949 if (isa
<CXXPseudoDestructorExpr
>(BME
)) {
20950 PD
= PDiag(diag::err_dtor_expr_without_call
) << /*pseudo-destructor*/ 1;
20951 } else if (const auto *ME
= dyn_cast
<MemberExpr
>(BME
)) {
20952 if (ME
->getMemberNameInfo().getName().getNameKind() ==
20953 DeclarationName::CXXDestructorName
)
20954 PD
= PDiag(diag::err_dtor_expr_without_call
) << /*destructor*/ 0;
20956 tryToRecoverWithCall(result
, PD
,
20957 /*complain*/ true);
20961 // ARC unbridged casts.
20962 case BuiltinType::ARCUnbridgedCast
: {
20963 Expr
*realCast
= ObjC().stripARCUnbridgedCast(E
);
20964 ObjC().diagnoseARCUnbridgedCast(realCast
);
20968 // Expressions of unknown type.
20969 case BuiltinType::UnknownAny
:
20970 return diagnoseUnknownAnyExpr(*this, E
);
20973 case BuiltinType::PseudoObject
:
20974 return PseudoObject().checkRValue(E
);
20976 case BuiltinType::BuiltinFn
: {
20977 // Accept __noop without parens by implicitly converting it to a call expr.
20978 auto *DRE
= dyn_cast
<DeclRefExpr
>(E
->IgnoreParenImpCasts());
20980 auto *FD
= cast
<FunctionDecl
>(DRE
->getDecl());
20981 unsigned BuiltinID
= FD
->getBuiltinID();
20982 if (BuiltinID
== Builtin::BI__noop
) {
20983 E
= ImpCastExprToType(E
, Context
.getPointerType(FD
->getType()),
20984 CK_BuiltinFnToFnPtr
)
20986 return CallExpr::Create(Context
, E
, /*Args=*/{}, Context
.IntTy
,
20987 VK_PRValue
, SourceLocation(),
20988 FPOptionsOverride());
20991 if (Context
.BuiltinInfo
.isInStdNamespace(BuiltinID
)) {
20992 // Any use of these other than a direct call is ill-formed as of C++20,
20993 // because they are not addressable functions. In earlier language
20994 // modes, warn and force an instantiation of the real body.
20995 Diag(E
->getBeginLoc(),
20996 getLangOpts().CPlusPlus20
20997 ? diag::err_use_of_unaddressable_function
20998 : diag::warn_cxx20_compat_use_of_unaddressable_function
);
20999 if (FD
->isImplicitlyInstantiable()) {
21000 // Require a definition here because a normal attempt at
21001 // instantiation for a builtin will be ignored, and we won't try
21002 // again later. We assume that the definition of the template
21003 // precedes this use.
21004 InstantiateFunctionDefinition(E
->getBeginLoc(), FD
,
21005 /*Recursive=*/false,
21006 /*DefinitionRequired=*/true,
21007 /*AtEndOfTU=*/false);
21009 // Produce a properly-typed reference to the function.
21011 SS
.Adopt(DRE
->getQualifierLoc());
21012 TemplateArgumentListInfo TemplateArgs
;
21013 DRE
->copyTemplateArgumentsInto(TemplateArgs
);
21014 return BuildDeclRefExpr(
21015 FD
, FD
->getType(), VK_LValue
, DRE
->getNameInfo(),
21016 DRE
->hasQualifier() ? &SS
: nullptr, DRE
->getFoundDecl(),
21017 DRE
->getTemplateKeywordLoc(),
21018 DRE
->hasExplicitTemplateArgs() ? &TemplateArgs
: nullptr);
21022 Diag(E
->getBeginLoc(), diag::err_builtin_fn_use
);
21023 return ExprError();
21026 case BuiltinType::IncompleteMatrixIdx
:
21027 Diag(cast
<MatrixSubscriptExpr
>(E
->IgnoreParens())
21030 diag::err_matrix_incomplete_index
);
21031 return ExprError();
21033 // Expressions of unknown type.
21034 case BuiltinType::ArraySection
:
21035 Diag(E
->getBeginLoc(), diag::err_array_section_use
)
21036 << cast
<ArraySectionExpr
>(E
)->isOMPArraySection();
21037 return ExprError();
21039 // Expressions of unknown type.
21040 case BuiltinType::OMPArrayShaping
:
21041 return ExprError(Diag(E
->getBeginLoc(), diag::err_omp_array_shaping_use
));
21043 case BuiltinType::OMPIterator
:
21044 return ExprError(Diag(E
->getBeginLoc(), diag::err_omp_iterator_use
));
21046 // Everything else should be impossible.
21047 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21048 case BuiltinType::Id:
21049 #include "clang/Basic/OpenCLImageTypes.def"
21050 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21051 case BuiltinType::Id:
21052 #include "clang/Basic/OpenCLExtensionTypes.def"
21053 #define SVE_TYPE(Name, Id, SingletonId) \
21054 case BuiltinType::Id:
21055 #include "clang/Basic/AArch64SVEACLETypes.def"
21056 #define PPC_VECTOR_TYPE(Name, Id, Size) \
21057 case BuiltinType::Id:
21058 #include "clang/Basic/PPCTypes.def"
21059 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21060 #include "clang/Basic/RISCVVTypes.def"
21061 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21062 #include "clang/Basic/WebAssemblyReferenceTypes.def"
21063 #define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
21064 #include "clang/Basic/AMDGPUTypes.def"
21065 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21066 #include "clang/Basic/HLSLIntangibleTypes.def"
21067 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21068 #define PLACEHOLDER_TYPE(Id, SingletonId)
21069 #include "clang/AST/BuiltinTypes.def"
21073 llvm_unreachable("invalid placeholder type!");
21076 bool Sema::CheckCaseExpression(Expr
*E
) {
21077 if (E
->isTypeDependent())
21079 if (E
->isValueDependent() || E
->isIntegerConstantExpr(Context
))
21080 return E
->getType()->isIntegralOrEnumerationType();
21084 ExprResult
Sema::CreateRecoveryExpr(SourceLocation Begin
, SourceLocation End
,
21085 ArrayRef
<Expr
*> SubExprs
, QualType T
) {
21086 if (!Context
.getLangOpts().RecoveryAST
)
21087 return ExprError();
21089 if (isSFINAEContext())
21090 return ExprError();
21092 if (T
.isNull() || T
->isUndeducedType() ||
21093 !Context
.getLangOpts().RecoveryASTType
)
21094 // We don't know the concrete type, fallback to dependent type.
21095 T
= Context
.DependentTy
;
21097 return RecoveryExpr::Create(Context
, T
, Begin
, End
, SubExprs
);