[Flang] remove whole-archive option for AIX linker (#76039)
[llvm-project.git] / clang / lib / Sema / SemaExpr.cpp
blob960f513d1111b2c71d0b001855106d2a52d02b33
1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements semantic analysis for expressions.
11 //===----------------------------------------------------------------------===//
13 #include "TreeTransform.h"
14 #include "UsedDeclVisitor.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/OperationKinds.h"
28 #include "clang/AST/ParentMapContext.h"
29 #include "clang/AST/RecursiveASTVisitor.h"
30 #include "clang/AST/Type.h"
31 #include "clang/AST/TypeLoc.h"
32 #include "clang/Basic/Builtins.h"
33 #include "clang/Basic/DiagnosticSema.h"
34 #include "clang/Basic/PartialDiagnostic.h"
35 #include "clang/Basic/SourceManager.h"
36 #include "clang/Basic/Specifiers.h"
37 #include "clang/Basic/TargetInfo.h"
38 #include "clang/Basic/TypeTraits.h"
39 #include "clang/Lex/LiteralSupport.h"
40 #include "clang/Lex/Preprocessor.h"
41 #include "clang/Sema/AnalysisBasedWarnings.h"
42 #include "clang/Sema/DeclSpec.h"
43 #include "clang/Sema/DelayedDiagnostic.h"
44 #include "clang/Sema/Designator.h"
45 #include "clang/Sema/EnterExpressionEvaluationContext.h"
46 #include "clang/Sema/Initialization.h"
47 #include "clang/Sema/Lookup.h"
48 #include "clang/Sema/Overload.h"
49 #include "clang/Sema/ParsedTemplate.h"
50 #include "clang/Sema/Scope.h"
51 #include "clang/Sema/ScopeInfo.h"
52 #include "clang/Sema/SemaFixItUtils.h"
53 #include "clang/Sema/SemaInternal.h"
54 #include "clang/Sema/Template.h"
55 #include "llvm/ADT/STLExtras.h"
56 #include "llvm/ADT/StringExtras.h"
57 #include "llvm/Support/Casting.h"
58 #include "llvm/Support/ConvertUTF.h"
59 #include "llvm/Support/SaveAndRestore.h"
60 #include "llvm/Support/TypeSize.h"
61 #include <optional>
63 using namespace clang;
64 using namespace sema;
66 /// Determine whether the use of this declaration is valid, without
67 /// emitting diagnostics.
68 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
69 // See if this is an auto-typed variable whose initializer we are parsing.
70 if (ParsingInitForAutoVars.count(D))
71 return false;
73 // See if this is a deleted function.
74 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
75 if (FD->isDeleted())
76 return false;
78 // If the function has a deduced return type, and we can't deduce it,
79 // then we can't use it either.
80 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
81 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
82 return false;
84 // See if this is an aligned allocation/deallocation function that is
85 // unavailable.
86 if (TreatUnavailableAsInvalid &&
87 isUnavailableAlignedAllocationFunction(*FD))
88 return false;
91 // See if this function is unavailable.
92 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
93 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
94 return false;
96 if (isa<UnresolvedUsingIfExistsDecl>(D))
97 return false;
99 return true;
102 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
103 // Warn if this is used but marked unused.
104 if (const auto *A = D->getAttr<UnusedAttr>()) {
105 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
106 // should diagnose them.
107 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
108 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
109 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
110 if (DC && !DC->hasAttr<UnusedAttr>())
111 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
116 /// Emit a note explaining that this function is deleted.
117 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
118 assert(Decl && Decl->isDeleted());
120 if (Decl->isDefaulted()) {
121 // If the method was explicitly defaulted, point at that declaration.
122 if (!Decl->isImplicit())
123 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
125 // Try to diagnose why this special member function was implicitly
126 // deleted. This might fail, if that reason no longer applies.
127 DiagnoseDeletedDefaultedFunction(Decl);
128 return;
131 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
132 if (Ctor && Ctor->isInheritingConstructor())
133 return NoteDeletedInheritingConstructor(Ctor);
135 Diag(Decl->getLocation(), diag::note_availability_specified_here)
136 << Decl << 1;
139 /// Determine whether a FunctionDecl was ever declared with an
140 /// explicit storage class.
141 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
142 for (auto *I : D->redecls()) {
143 if (I->getStorageClass() != SC_None)
144 return true;
146 return false;
149 /// Check whether we're in an extern inline function and referring to a
150 /// variable or function with internal linkage (C11 6.7.4p3).
152 /// This is only a warning because we used to silently accept this code, but
153 /// in many cases it will not behave correctly. This is not enabled in C++ mode
154 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
155 /// and so while there may still be user mistakes, most of the time we can't
156 /// prove that there are errors.
157 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
158 const NamedDecl *D,
159 SourceLocation Loc) {
160 // This is disabled under C++; there are too many ways for this to fire in
161 // contexts where the warning is a false positive, or where it is technically
162 // correct but benign.
163 if (S.getLangOpts().CPlusPlus)
164 return;
166 // Check if this is an inlined function or method.
167 FunctionDecl *Current = S.getCurFunctionDecl();
168 if (!Current)
169 return;
170 if (!Current->isInlined())
171 return;
172 if (!Current->isExternallyVisible())
173 return;
175 // Check if the decl has internal linkage.
176 if (D->getFormalLinkage() != Linkage::Internal)
177 return;
179 // Downgrade from ExtWarn to Extension if
180 // (1) the supposedly external inline function is in the main file,
181 // and probably won't be included anywhere else.
182 // (2) the thing we're referencing is a pure function.
183 // (3) the thing we're referencing is another inline function.
184 // This last can give us false negatives, but it's better than warning on
185 // wrappers for simple C library functions.
186 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
187 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
188 if (!DowngradeWarning && UsedFn)
189 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
191 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
192 : diag::ext_internal_in_extern_inline)
193 << /*IsVar=*/!UsedFn << D;
195 S.MaybeSuggestAddingStaticToDecl(Current);
197 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
198 << D;
201 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
202 const FunctionDecl *First = Cur->getFirstDecl();
204 // Suggest "static" on the function, if possible.
205 if (!hasAnyExplicitStorageClass(First)) {
206 SourceLocation DeclBegin = First->getSourceRange().getBegin();
207 Diag(DeclBegin, diag::note_convert_inline_to_static)
208 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
212 /// Determine whether the use of this declaration is valid, and
213 /// emit any corresponding diagnostics.
215 /// This routine diagnoses various problems with referencing
216 /// declarations that can occur when using a declaration. For example,
217 /// it might warn if a deprecated or unavailable declaration is being
218 /// used, or produce an error (and return true) if a C++0x deleted
219 /// function is being used.
221 /// \returns true if there was an error (this declaration cannot be
222 /// referenced), false otherwise.
224 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
225 const ObjCInterfaceDecl *UnknownObjCClass,
226 bool ObjCPropertyAccess,
227 bool AvoidPartialAvailabilityChecks,
228 ObjCInterfaceDecl *ClassReceiver,
229 bool SkipTrailingRequiresClause) {
230 SourceLocation Loc = Locs.front();
231 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
232 // If there were any diagnostics suppressed by template argument deduction,
233 // emit them now.
234 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
235 if (Pos != SuppressedDiagnostics.end()) {
236 for (const PartialDiagnosticAt &Suppressed : Pos->second)
237 Diag(Suppressed.first, Suppressed.second);
239 // Clear out the list of suppressed diagnostics, so that we don't emit
240 // them again for this specialization. However, we don't obsolete this
241 // entry from the table, because we want to avoid ever emitting these
242 // diagnostics again.
243 Pos->second.clear();
246 // C++ [basic.start.main]p3:
247 // The function 'main' shall not be used within a program.
248 if (cast<FunctionDecl>(D)->isMain())
249 Diag(Loc, diag::ext_main_used);
251 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
254 // See if this is an auto-typed variable whose initializer we are parsing.
255 if (ParsingInitForAutoVars.count(D)) {
256 if (isa<BindingDecl>(D)) {
257 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
258 << D->getDeclName();
259 } else {
260 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
261 << D->getDeclName() << cast<VarDecl>(D)->getType();
263 return true;
266 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
267 // See if this is a deleted function.
268 if (FD->isDeleted()) {
269 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
270 if (Ctor && Ctor->isInheritingConstructor())
271 Diag(Loc, diag::err_deleted_inherited_ctor_use)
272 << Ctor->getParent()
273 << Ctor->getInheritedConstructor().getConstructor()->getParent();
274 else
275 Diag(Loc, diag::err_deleted_function_use);
276 NoteDeletedFunction(FD);
277 return true;
280 // [expr.prim.id]p4
281 // A program that refers explicitly or implicitly to a function with a
282 // trailing requires-clause whose constraint-expression is not satisfied,
283 // other than to declare it, is ill-formed. [...]
285 // See if this is a function with constraints that need to be satisfied.
286 // Check this before deducing the return type, as it might instantiate the
287 // definition.
288 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
289 ConstraintSatisfaction Satisfaction;
290 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
291 /*ForOverloadResolution*/ true))
292 // A diagnostic will have already been generated (non-constant
293 // constraint expression, for example)
294 return true;
295 if (!Satisfaction.IsSatisfied) {
296 Diag(Loc,
297 diag::err_reference_to_function_with_unsatisfied_constraints)
298 << D;
299 DiagnoseUnsatisfiedConstraint(Satisfaction);
300 return true;
304 // If the function has a deduced return type, and we can't deduce it,
305 // then we can't use it either.
306 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
307 DeduceReturnType(FD, Loc))
308 return true;
310 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
311 return true;
315 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
316 // Lambdas are only default-constructible or assignable in C++2a onwards.
317 if (MD->getParent()->isLambda() &&
318 ((isa<CXXConstructorDecl>(MD) &&
319 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
320 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
321 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
322 << !isa<CXXConstructorDecl>(MD);
326 auto getReferencedObjCProp = [](const NamedDecl *D) ->
327 const ObjCPropertyDecl * {
328 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
329 return MD->findPropertyDecl();
330 return nullptr;
332 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
333 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
334 return true;
335 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
336 return true;
339 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
340 // Only the variables omp_in and omp_out are allowed in the combiner.
341 // Only the variables omp_priv and omp_orig are allowed in the
342 // initializer-clause.
343 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
344 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
345 isa<VarDecl>(D)) {
346 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
347 << getCurFunction()->HasOMPDeclareReductionCombiner;
348 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
349 return true;
352 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
353 // List-items in map clauses on this construct may only refer to the declared
354 // variable var and entities that could be referenced by a procedure defined
355 // at the same location.
356 // [OpenMP 5.2] Also allow iterator declared variables.
357 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
358 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
359 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
360 << getOpenMPDeclareMapperVarName();
361 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
362 return true;
365 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
366 Diag(Loc, diag::err_use_of_empty_using_if_exists);
367 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
368 return true;
371 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
372 AvoidPartialAvailabilityChecks, ClassReceiver);
374 DiagnoseUnusedOfDecl(*this, D, Loc);
376 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
378 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
379 if (getLangOpts().getFPEvalMethod() !=
380 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine &&
381 PP.getLastFPEvalPragmaLocation().isValid() &&
382 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
383 Diag(D->getLocation(),
384 diag::err_type_available_only_in_default_eval_method)
385 << D->getName();
388 if (auto *VD = dyn_cast<ValueDecl>(D))
389 checkTypeSupport(VD->getType(), Loc, VD);
391 if (LangOpts.SYCLIsDevice ||
392 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
393 if (!Context.getTargetInfo().isTLSSupported())
394 if (const auto *VD = dyn_cast<VarDecl>(D))
395 if (VD->getTLSKind() != VarDecl::TLS_None)
396 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
399 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
400 !isUnevaluatedContext()) {
401 // C++ [expr.prim.req.nested] p3
402 // A local parameter shall only appear as an unevaluated operand
403 // (Clause 8) within the constraint-expression.
404 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
405 << D;
406 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
407 return true;
410 return false;
413 /// DiagnoseSentinelCalls - This routine checks whether a call or
414 /// message-send is to a declaration with the sentinel attribute, and
415 /// if so, it checks that the requirements of the sentinel are
416 /// satisfied.
417 void Sema::DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,
418 ArrayRef<Expr *> Args) {
419 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
420 if (!Attr)
421 return;
423 // The number of formal parameters of the declaration.
424 unsigned NumFormalParams;
426 // The kind of declaration. This is also an index into a %select in
427 // the diagnostic.
428 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
430 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
431 NumFormalParams = MD->param_size();
432 CalleeKind = CK_Method;
433 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
434 NumFormalParams = FD->param_size();
435 CalleeKind = CK_Function;
436 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
437 QualType Ty = VD->getType();
438 const FunctionType *Fn = nullptr;
439 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
440 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
441 if (!Fn)
442 return;
443 CalleeKind = CK_Function;
444 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
445 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
446 CalleeKind = CK_Block;
447 } else {
448 return;
451 if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
452 NumFormalParams = proto->getNumParams();
453 else
454 NumFormalParams = 0;
455 } else {
456 return;
459 // "NullPos" is the number of formal parameters at the end which
460 // effectively count as part of the variadic arguments. This is
461 // useful if you would prefer to not have *any* formal parameters,
462 // but the language forces you to have at least one.
463 unsigned NullPos = Attr->getNullPos();
464 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
465 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
467 // The number of arguments which should follow the sentinel.
468 unsigned NumArgsAfterSentinel = Attr->getSentinel();
470 // If there aren't enough arguments for all the formal parameters,
471 // the sentinel, and the args after the sentinel, complain.
472 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
473 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
474 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
475 return;
478 // Otherwise, find the sentinel expression.
479 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
480 if (!SentinelExpr)
481 return;
482 if (SentinelExpr->isValueDependent())
483 return;
484 if (Context.isSentinelNullExpr(SentinelExpr))
485 return;
487 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
488 // or 'NULL' if those are actually defined in the context. Only use
489 // 'nil' for ObjC methods, where it's much more likely that the
490 // variadic arguments form a list of object pointers.
491 SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
492 std::string NullValue;
493 if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
494 NullValue = "nil";
495 else if (getLangOpts().CPlusPlus11)
496 NullValue = "nullptr";
497 else if (PP.isMacroDefined("NULL"))
498 NullValue = "NULL";
499 else
500 NullValue = "(void*) 0";
502 if (MissingNilLoc.isInvalid())
503 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
504 else
505 Diag(MissingNilLoc, diag::warn_missing_sentinel)
506 << int(CalleeKind)
507 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
508 Diag(D->getLocation(), diag::note_sentinel_here)
509 << int(CalleeKind) << Attr->getRange();
512 SourceRange Sema::getExprRange(Expr *E) const {
513 return E ? E->getSourceRange() : SourceRange();
516 //===----------------------------------------------------------------------===//
517 // Standard Promotions and Conversions
518 //===----------------------------------------------------------------------===//
520 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
521 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
522 // Handle any placeholder expressions which made it here.
523 if (E->hasPlaceholderType()) {
524 ExprResult result = CheckPlaceholderExpr(E);
525 if (result.isInvalid()) return ExprError();
526 E = result.get();
529 QualType Ty = E->getType();
530 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
532 if (Ty->isFunctionType()) {
533 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
534 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
535 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
536 return ExprError();
538 E = ImpCastExprToType(E, Context.getPointerType(Ty),
539 CK_FunctionToPointerDecay).get();
540 } else if (Ty->isArrayType()) {
541 // In C90 mode, arrays only promote to pointers if the array expression is
542 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
543 // type 'array of type' is converted to an expression that has type 'pointer
544 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
545 // that has type 'array of type' ...". The relevant change is "an lvalue"
546 // (C90) to "an expression" (C99).
548 // C++ 4.2p1:
549 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
550 // T" can be converted to an rvalue of type "pointer to T".
552 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
553 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
554 CK_ArrayToPointerDecay);
555 if (Res.isInvalid())
556 return ExprError();
557 E = Res.get();
560 return E;
563 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
564 // Check to see if we are dereferencing a null pointer. If so,
565 // and if not volatile-qualified, this is undefined behavior that the
566 // optimizer will delete, so warn about it. People sometimes try to use this
567 // to get a deterministic trap and are surprised by clang's behavior. This
568 // only handles the pattern "*null", which is a very syntactic check.
569 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
570 if (UO && UO->getOpcode() == UO_Deref &&
571 UO->getSubExpr()->getType()->isPointerType()) {
572 const LangAS AS =
573 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
574 if ((!isTargetAddressSpace(AS) ||
575 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
576 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
577 S.Context, Expr::NPC_ValueDependentIsNotNull) &&
578 !UO->getType().isVolatileQualified()) {
579 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
580 S.PDiag(diag::warn_indirection_through_null)
581 << UO->getSubExpr()->getSourceRange());
582 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
583 S.PDiag(diag::note_indirection_through_null));
588 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
589 SourceLocation AssignLoc,
590 const Expr* RHS) {
591 const ObjCIvarDecl *IV = OIRE->getDecl();
592 if (!IV)
593 return;
595 DeclarationName MemberName = IV->getDeclName();
596 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
597 if (!Member || !Member->isStr("isa"))
598 return;
600 const Expr *Base = OIRE->getBase();
601 QualType BaseType = Base->getType();
602 if (OIRE->isArrow())
603 BaseType = BaseType->getPointeeType();
604 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
605 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
606 ObjCInterfaceDecl *ClassDeclared = nullptr;
607 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
608 if (!ClassDeclared->getSuperClass()
609 && (*ClassDeclared->ivar_begin()) == IV) {
610 if (RHS) {
611 NamedDecl *ObjectSetClass =
612 S.LookupSingleName(S.TUScope,
613 &S.Context.Idents.get("object_setClass"),
614 SourceLocation(), S.LookupOrdinaryName);
615 if (ObjectSetClass) {
616 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
617 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
618 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
619 "object_setClass(")
620 << FixItHint::CreateReplacement(
621 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
622 << FixItHint::CreateInsertion(RHSLocEnd, ")");
624 else
625 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
626 } else {
627 NamedDecl *ObjectGetClass =
628 S.LookupSingleName(S.TUScope,
629 &S.Context.Idents.get("object_getClass"),
630 SourceLocation(), S.LookupOrdinaryName);
631 if (ObjectGetClass)
632 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
633 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
634 "object_getClass(")
635 << FixItHint::CreateReplacement(
636 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
637 else
638 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
640 S.Diag(IV->getLocation(), diag::note_ivar_decl);
645 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
646 // Handle any placeholder expressions which made it here.
647 if (E->hasPlaceholderType()) {
648 ExprResult result = CheckPlaceholderExpr(E);
649 if (result.isInvalid()) return ExprError();
650 E = result.get();
653 // C++ [conv.lval]p1:
654 // A glvalue of a non-function, non-array type T can be
655 // converted to a prvalue.
656 if (!E->isGLValue()) return E;
658 QualType T = E->getType();
659 assert(!T.isNull() && "r-value conversion on typeless expression?");
661 // lvalue-to-rvalue conversion cannot be applied to function or array types.
662 if (T->isFunctionType() || T->isArrayType())
663 return E;
665 // We don't want to throw lvalue-to-rvalue casts on top of
666 // expressions of certain types in C++.
667 if (getLangOpts().CPlusPlus &&
668 (E->getType() == Context.OverloadTy ||
669 T->isDependentType() ||
670 T->isRecordType()))
671 return E;
673 // The C standard is actually really unclear on this point, and
674 // DR106 tells us what the result should be but not why. It's
675 // generally best to say that void types just doesn't undergo
676 // lvalue-to-rvalue at all. Note that expressions of unqualified
677 // 'void' type are never l-values, but qualified void can be.
678 if (T->isVoidType())
679 return E;
681 // OpenCL usually rejects direct accesses to values of 'half' type.
682 if (getLangOpts().OpenCL &&
683 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
684 T->isHalfType()) {
685 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
686 << 0 << T;
687 return ExprError();
690 CheckForNullPointerDereference(*this, E);
691 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
692 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
693 &Context.Idents.get("object_getClass"),
694 SourceLocation(), LookupOrdinaryName);
695 if (ObjectGetClass)
696 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
697 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
698 << FixItHint::CreateReplacement(
699 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
700 else
701 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
703 else if (const ObjCIvarRefExpr *OIRE =
704 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
705 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
707 // C++ [conv.lval]p1:
708 // [...] If T is a non-class type, the type of the prvalue is the
709 // cv-unqualified version of T. Otherwise, the type of the
710 // rvalue is T.
712 // C99 6.3.2.1p2:
713 // If the lvalue has qualified type, the value has the unqualified
714 // version of the type of the lvalue; otherwise, the value has the
715 // type of the lvalue.
716 if (T.hasQualifiers())
717 T = T.getUnqualifiedType();
719 // Under the MS ABI, lock down the inheritance model now.
720 if (T->isMemberPointerType() &&
721 Context.getTargetInfo().getCXXABI().isMicrosoft())
722 (void)isCompleteType(E->getExprLoc(), T);
724 ExprResult Res = CheckLValueToRValueConversionOperand(E);
725 if (Res.isInvalid())
726 return Res;
727 E = Res.get();
729 // Loading a __weak object implicitly retains the value, so we need a cleanup to
730 // balance that.
731 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
732 Cleanup.setExprNeedsCleanups(true);
734 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
735 Cleanup.setExprNeedsCleanups(true);
737 // C++ [conv.lval]p3:
738 // If T is cv std::nullptr_t, the result is a null pointer constant.
739 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
740 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
741 CurFPFeatureOverrides());
743 // C11 6.3.2.1p2:
744 // ... if the lvalue has atomic type, the value has the non-atomic version
745 // of the type of the lvalue ...
746 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
747 T = Atomic->getValueType().getUnqualifiedType();
748 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
749 nullptr, VK_PRValue, FPOptionsOverride());
752 return Res;
755 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
756 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
757 if (Res.isInvalid())
758 return ExprError();
759 Res = DefaultLvalueConversion(Res.get());
760 if (Res.isInvalid())
761 return ExprError();
762 return Res;
765 /// CallExprUnaryConversions - a special case of an unary conversion
766 /// performed on a function designator of a call expression.
767 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
768 QualType Ty = E->getType();
769 ExprResult Res = E;
770 // Only do implicit cast for a function type, but not for a pointer
771 // to function type.
772 if (Ty->isFunctionType()) {
773 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
774 CK_FunctionToPointerDecay);
775 if (Res.isInvalid())
776 return ExprError();
778 Res = DefaultLvalueConversion(Res.get());
779 if (Res.isInvalid())
780 return ExprError();
781 return Res.get();
784 /// UsualUnaryConversions - Performs various conversions that are common to most
785 /// operators (C99 6.3). The conversions of array and function types are
786 /// sometimes suppressed. For example, the array->pointer conversion doesn't
787 /// apply if the array is an argument to the sizeof or address (&) operators.
788 /// In these instances, this routine should *not* be called.
789 ExprResult Sema::UsualUnaryConversions(Expr *E) {
790 // First, convert to an r-value.
791 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
792 if (Res.isInvalid())
793 return ExprError();
794 E = Res.get();
796 QualType Ty = E->getType();
797 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
799 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
800 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
801 (getLangOpts().getFPEvalMethod() !=
802 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
803 PP.getLastFPEvalPragmaLocation().isValid())) {
804 switch (EvalMethod) {
805 default:
806 llvm_unreachable("Unrecognized float evaluation method");
807 break;
808 case LangOptions::FEM_UnsetOnCommandLine:
809 llvm_unreachable("Float evaluation method should be set by now");
810 break;
811 case LangOptions::FEM_Double:
812 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
813 // Widen the expression to double.
814 return Ty->isComplexType()
815 ? ImpCastExprToType(E,
816 Context.getComplexType(Context.DoubleTy),
817 CK_FloatingComplexCast)
818 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
819 break;
820 case LangOptions::FEM_Extended:
821 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
822 // Widen the expression to long double.
823 return Ty->isComplexType()
824 ? ImpCastExprToType(
825 E, Context.getComplexType(Context.LongDoubleTy),
826 CK_FloatingComplexCast)
827 : ImpCastExprToType(E, Context.LongDoubleTy,
828 CK_FloatingCast);
829 break;
833 // Half FP have to be promoted to float unless it is natively supported
834 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
835 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
837 // Try to perform integral promotions if the object has a theoretically
838 // promotable type.
839 if (Ty->isIntegralOrUnscopedEnumerationType()) {
840 // C99 6.3.1.1p2:
842 // The following may be used in an expression wherever an int or
843 // unsigned int may be used:
844 // - an object or expression with an integer type whose integer
845 // conversion rank is less than or equal to the rank of int
846 // and unsigned int.
847 // - A bit-field of type _Bool, int, signed int, or unsigned int.
849 // If an int can represent all values of the original type, the
850 // value is converted to an int; otherwise, it is converted to an
851 // unsigned int. These are called the integer promotions. All
852 // other types are unchanged by the integer promotions.
854 QualType PTy = Context.isPromotableBitField(E);
855 if (!PTy.isNull()) {
856 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
857 return E;
859 if (Context.isPromotableIntegerType(Ty)) {
860 QualType PT = Context.getPromotedIntegerType(Ty);
861 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
862 return E;
865 return E;
868 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
869 /// do not have a prototype. Arguments that have type float or __fp16
870 /// are promoted to double. All other argument types are converted by
871 /// UsualUnaryConversions().
872 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
873 QualType Ty = E->getType();
874 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
876 ExprResult Res = UsualUnaryConversions(E);
877 if (Res.isInvalid())
878 return ExprError();
879 E = Res.get();
881 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
882 // promote to double.
883 // Note that default argument promotion applies only to float (and
884 // half/fp16); it does not apply to _Float16.
885 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
886 if (BTy && (BTy->getKind() == BuiltinType::Half ||
887 BTy->getKind() == BuiltinType::Float)) {
888 if (getLangOpts().OpenCL &&
889 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
890 if (BTy->getKind() == BuiltinType::Half) {
891 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
893 } else {
894 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
897 if (BTy &&
898 getLangOpts().getExtendIntArgs() ==
899 LangOptions::ExtendArgsKind::ExtendTo64 &&
900 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
901 Context.getTypeSizeInChars(BTy) <
902 Context.getTypeSizeInChars(Context.LongLongTy)) {
903 E = (Ty->isUnsignedIntegerType())
904 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
905 .get()
906 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
907 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
908 "Unexpected typesize for LongLongTy");
911 // C++ performs lvalue-to-rvalue conversion as a default argument
912 // promotion, even on class types, but note:
913 // C++11 [conv.lval]p2:
914 // When an lvalue-to-rvalue conversion occurs in an unevaluated
915 // operand or a subexpression thereof the value contained in the
916 // referenced object is not accessed. Otherwise, if the glvalue
917 // has a class type, the conversion copy-initializes a temporary
918 // of type T from the glvalue and the result of the conversion
919 // is a prvalue for the temporary.
920 // FIXME: add some way to gate this entire thing for correctness in
921 // potentially potentially evaluated contexts.
922 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
923 ExprResult Temp = PerformCopyInitialization(
924 InitializedEntity::InitializeTemporary(E->getType()),
925 E->getExprLoc(), E);
926 if (Temp.isInvalid())
927 return ExprError();
928 E = Temp.get();
931 return E;
934 /// Determine the degree of POD-ness for an expression.
935 /// Incomplete types are considered POD, since this check can be performed
936 /// when we're in an unevaluated context.
937 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
938 if (Ty->isIncompleteType()) {
939 // C++11 [expr.call]p7:
940 // After these conversions, if the argument does not have arithmetic,
941 // enumeration, pointer, pointer to member, or class type, the program
942 // is ill-formed.
944 // Since we've already performed array-to-pointer and function-to-pointer
945 // decay, the only such type in C++ is cv void. This also handles
946 // initializer lists as variadic arguments.
947 if (Ty->isVoidType())
948 return VAK_Invalid;
950 if (Ty->isObjCObjectType())
951 return VAK_Invalid;
952 return VAK_Valid;
955 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
956 return VAK_Invalid;
958 if (Context.getTargetInfo().getTriple().isWasm() &&
959 Ty.isWebAssemblyReferenceType()) {
960 return VAK_Invalid;
963 if (Ty.isCXX98PODType(Context))
964 return VAK_Valid;
966 // C++11 [expr.call]p7:
967 // Passing a potentially-evaluated argument of class type (Clause 9)
968 // having a non-trivial copy constructor, a non-trivial move constructor,
969 // or a non-trivial destructor, with no corresponding parameter,
970 // is conditionally-supported with implementation-defined semantics.
971 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
972 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
973 if (!Record->hasNonTrivialCopyConstructor() &&
974 !Record->hasNonTrivialMoveConstructor() &&
975 !Record->hasNonTrivialDestructor())
976 return VAK_ValidInCXX11;
978 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
979 return VAK_Valid;
981 if (Ty->isObjCObjectType())
982 return VAK_Invalid;
984 if (getLangOpts().MSVCCompat)
985 return VAK_MSVCUndefined;
987 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
988 // permitted to reject them. We should consider doing so.
989 return VAK_Undefined;
992 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
993 // Don't allow one to pass an Objective-C interface to a vararg.
994 const QualType &Ty = E->getType();
995 VarArgKind VAK = isValidVarArgType(Ty);
997 // Complain about passing non-POD types through varargs.
998 switch (VAK) {
999 case VAK_ValidInCXX11:
1000 DiagRuntimeBehavior(
1001 E->getBeginLoc(), nullptr,
1002 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1003 [[fallthrough]];
1004 case VAK_Valid:
1005 if (Ty->isRecordType()) {
1006 // This is unlikely to be what the user intended. If the class has a
1007 // 'c_str' member function, the user probably meant to call that.
1008 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1009 PDiag(diag::warn_pass_class_arg_to_vararg)
1010 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1012 break;
1014 case VAK_Undefined:
1015 case VAK_MSVCUndefined:
1016 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1017 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1018 << getLangOpts().CPlusPlus11 << Ty << CT);
1019 break;
1021 case VAK_Invalid:
1022 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
1023 Diag(E->getBeginLoc(),
1024 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1025 << Ty << CT;
1026 else if (Ty->isObjCObjectType())
1027 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1028 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1029 << Ty << CT);
1030 else
1031 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1032 << isa<InitListExpr>(E) << Ty << CT;
1033 break;
1037 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1038 /// will create a trap if the resulting type is not a POD type.
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 = stripARCUnbridgedCast(E);
1048 // Otherwise, do normal placeholder checking.
1049 } else {
1050 ExprResult ExprRes = CheckPlaceholderExpr(E);
1051 if (ExprRes.isInvalid())
1052 return ExprError();
1053 E = ExprRes.get();
1057 ExprResult ExprRes = DefaultArgumentPromotion(E);
1058 if (ExprRes.isInvalid())
1059 return ExprError();
1061 // Copy blocks to the heap.
1062 if (ExprRes.get()->getType()->isBlockPointerType())
1063 maybeExtendBlockObject(ExprRes);
1065 E = ExprRes.get();
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.
1071 CXXScopeSpec SS;
1072 SourceLocation TemplateKWLoc;
1073 UnqualifiedId Name;
1074 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1075 E->getBeginLoc());
1076 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1077 /*HasTrailingLParen=*/true,
1078 /*IsAddressOfOperand=*/false);
1079 if (TrapFn.isInvalid())
1080 return ExprError();
1082 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1083 std::nullopt, E->getEndLoc());
1084 if (Call.isInvalid())
1085 return ExprError();
1087 ExprResult Comma =
1088 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1089 if (Comma.isInvalid())
1090 return ExprError();
1091 return Comma.get();
1094 if (!getLangOpts().CPlusPlus &&
1095 RequireCompleteType(E->getExprLoc(), E->getType(),
1096 diag::err_call_incomplete_argument))
1097 return ExprError();
1099 return E;
1102 /// Converts an integer to complex float type. Helper function of
1103 /// UsualArithmeticConversions()
1105 /// \return false if the integer expression is an integer type and is
1106 /// successfully converted to the complex type.
1107 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1108 ExprResult &ComplexExpr,
1109 QualType IntTy,
1110 QualType ComplexTy,
1111 bool SkipCast) {
1112 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1113 if (SkipCast) return false;
1114 if (IntTy->isIntegerType()) {
1115 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1116 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1117 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1118 CK_FloatingRealToComplex);
1119 } else {
1120 assert(IntTy->isComplexIntegerType());
1121 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1122 CK_IntegralComplexToFloatingComplex);
1124 return false;
1127 // This handles complex/complex, complex/float, or float/complex.
1128 // When both operands are complex, the shorter operand is converted to the
1129 // type of the longer, and that is the type of the result. This corresponds
1130 // to what is done when combining two real floating-point operands.
1131 // The fun begins when size promotion occur across type domains.
1132 // From H&S 6.3.4: When one operand is complex and the other is a real
1133 // floating-point type, the less precise type is converted, within it's
1134 // real or complex domain, to the precision of the other type. For example,
1135 // when combining a "long double" with a "double _Complex", the
1136 // "double _Complex" is promoted to "long double _Complex".
1137 static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter,
1138 QualType ShorterType,
1139 QualType LongerType,
1140 bool PromotePrecision) {
1141 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1142 QualType Result =
1143 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1145 if (PromotePrecision) {
1146 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1147 Shorter =
1148 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1149 } else {
1150 if (LongerIsComplex)
1151 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1152 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1155 return Result;
1158 /// Handle arithmetic conversion with complex types. Helper function of
1159 /// UsualArithmeticConversions()
1160 static QualType handleComplexConversion(Sema &S, ExprResult &LHS,
1161 ExprResult &RHS, QualType LHSType,
1162 QualType RHSType, bool IsCompAssign) {
1163 // if we have an integer operand, the result is the complex type.
1164 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1165 /*SkipCast=*/false))
1166 return LHSType;
1167 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1168 /*SkipCast=*/IsCompAssign))
1169 return RHSType;
1171 // Compute the rank of the two types, regardless of whether they are complex.
1172 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1173 if (Order < 0)
1174 // Promote the precision of the LHS if not an assignment.
1175 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1176 /*PromotePrecision=*/!IsCompAssign);
1177 // Promote the precision of the RHS unless it is already the same as the LHS.
1178 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1179 /*PromotePrecision=*/Order > 0);
1182 /// Handle arithmetic conversion from integer to float. Helper function
1183 /// of UsualArithmeticConversions()
1184 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1185 ExprResult &IntExpr,
1186 QualType FloatTy, QualType IntTy,
1187 bool ConvertFloat, bool ConvertInt) {
1188 if (IntTy->isIntegerType()) {
1189 if (ConvertInt)
1190 // Convert intExpr to the lhs floating point type.
1191 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1192 CK_IntegralToFloating);
1193 return FloatTy;
1196 // Convert both sides to the appropriate complex float.
1197 assert(IntTy->isComplexIntegerType());
1198 QualType result = S.Context.getComplexType(FloatTy);
1200 // _Complex int -> _Complex float
1201 if (ConvertInt)
1202 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1203 CK_IntegralComplexToFloatingComplex);
1205 // float -> _Complex float
1206 if (ConvertFloat)
1207 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1208 CK_FloatingRealToComplex);
1210 return result;
1213 /// Handle arithmethic conversion with floating point types. Helper
1214 /// function of UsualArithmeticConversions()
1215 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1216 ExprResult &RHS, QualType LHSType,
1217 QualType RHSType, bool IsCompAssign) {
1218 bool LHSFloat = LHSType->isRealFloatingType();
1219 bool RHSFloat = RHSType->isRealFloatingType();
1221 // N1169 4.1.4: If one of the operands has a floating type and the other
1222 // operand has a fixed-point type, the fixed-point operand
1223 // is converted to the floating type [...]
1224 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1225 if (LHSFloat)
1226 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1227 else if (!IsCompAssign)
1228 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1229 return LHSFloat ? LHSType : RHSType;
1232 // If we have two real floating types, convert the smaller operand
1233 // to the bigger result.
1234 if (LHSFloat && RHSFloat) {
1235 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1236 if (order > 0) {
1237 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1238 return LHSType;
1241 assert(order < 0 && "illegal float comparison");
1242 if (!IsCompAssign)
1243 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1244 return RHSType;
1247 if (LHSFloat) {
1248 // Half FP has to be promoted to float unless it is natively supported
1249 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1250 LHSType = S.Context.FloatTy;
1252 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1253 /*ConvertFloat=*/!IsCompAssign,
1254 /*ConvertInt=*/ true);
1256 assert(RHSFloat);
1257 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1258 /*ConvertFloat=*/ true,
1259 /*ConvertInt=*/!IsCompAssign);
1262 /// Diagnose attempts to convert between __float128, __ibm128 and
1263 /// long double if there is no support for such conversion.
1264 /// Helper function of UsualArithmeticConversions().
1265 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1266 QualType RHSType) {
1267 // No issue if either is not a floating point type.
1268 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1269 return false;
1271 // No issue if both have the same 128-bit float semantics.
1272 auto *LHSComplex = LHSType->getAs<ComplexType>();
1273 auto *RHSComplex = RHSType->getAs<ComplexType>();
1275 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1276 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1278 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1279 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1281 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1282 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1283 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1284 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1285 return false;
1287 return true;
1290 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1292 namespace {
1293 /// These helper callbacks are placed in an anonymous namespace to
1294 /// permit their use as function template parameters.
1295 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1296 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1299 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1300 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1301 CK_IntegralComplexCast);
1305 /// Handle integer arithmetic conversions. Helper function of
1306 /// UsualArithmeticConversions()
1307 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1308 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1309 ExprResult &RHS, QualType LHSType,
1310 QualType RHSType, bool IsCompAssign) {
1311 // The rules for this case are in C99 6.3.1.8
1312 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1313 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1314 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1315 if (LHSSigned == RHSSigned) {
1316 // Same signedness; use the higher-ranked type
1317 if (order >= 0) {
1318 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1319 return LHSType;
1320 } else if (!IsCompAssign)
1321 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1322 return RHSType;
1323 } else if (order != (LHSSigned ? 1 : -1)) {
1324 // The unsigned type has greater than or equal rank to the
1325 // signed type, so use the unsigned type
1326 if (RHSSigned) {
1327 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1328 return LHSType;
1329 } else if (!IsCompAssign)
1330 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1331 return RHSType;
1332 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1333 // The two types are different widths; if we are here, that
1334 // means the signed type is larger than the unsigned type, so
1335 // use the signed type.
1336 if (LHSSigned) {
1337 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1338 return LHSType;
1339 } else if (!IsCompAssign)
1340 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1341 return RHSType;
1342 } else {
1343 // The signed type is higher-ranked than the unsigned type,
1344 // but isn't actually any bigger (like unsigned int and long
1345 // on most 32-bit systems). Use the unsigned type corresponding
1346 // to the signed type.
1347 QualType result =
1348 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1349 RHS = (*doRHSCast)(S, RHS.get(), result);
1350 if (!IsCompAssign)
1351 LHS = (*doLHSCast)(S, LHS.get(), result);
1352 return result;
1356 /// Handle conversions with GCC complex int extension. Helper function
1357 /// of UsualArithmeticConversions()
1358 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1359 ExprResult &RHS, QualType LHSType,
1360 QualType RHSType,
1361 bool IsCompAssign) {
1362 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1363 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1365 if (LHSComplexInt && RHSComplexInt) {
1366 QualType LHSEltType = LHSComplexInt->getElementType();
1367 QualType RHSEltType = RHSComplexInt->getElementType();
1368 QualType ScalarType =
1369 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1370 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1372 return S.Context.getComplexType(ScalarType);
1375 if (LHSComplexInt) {
1376 QualType LHSEltType = LHSComplexInt->getElementType();
1377 QualType ScalarType =
1378 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1379 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1380 QualType ComplexType = S.Context.getComplexType(ScalarType);
1381 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1382 CK_IntegralRealToComplex);
1384 return ComplexType;
1387 assert(RHSComplexInt);
1389 QualType RHSEltType = RHSComplexInt->getElementType();
1390 QualType ScalarType =
1391 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1392 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1393 QualType ComplexType = S.Context.getComplexType(ScalarType);
1395 if (!IsCompAssign)
1396 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1397 CK_IntegralRealToComplex);
1398 return ComplexType;
1401 /// Return the rank of a given fixed point or integer type. The value itself
1402 /// doesn't matter, but the values must be increasing with proper increasing
1403 /// rank as described in N1169 4.1.1.
1404 static unsigned GetFixedPointRank(QualType Ty) {
1405 const auto *BTy = Ty->getAs<BuiltinType>();
1406 assert(BTy && "Expected a builtin type.");
1408 switch (BTy->getKind()) {
1409 case BuiltinType::ShortFract:
1410 case BuiltinType::UShortFract:
1411 case BuiltinType::SatShortFract:
1412 case BuiltinType::SatUShortFract:
1413 return 1;
1414 case BuiltinType::Fract:
1415 case BuiltinType::UFract:
1416 case BuiltinType::SatFract:
1417 case BuiltinType::SatUFract:
1418 return 2;
1419 case BuiltinType::LongFract:
1420 case BuiltinType::ULongFract:
1421 case BuiltinType::SatLongFract:
1422 case BuiltinType::SatULongFract:
1423 return 3;
1424 case BuiltinType::ShortAccum:
1425 case BuiltinType::UShortAccum:
1426 case BuiltinType::SatShortAccum:
1427 case BuiltinType::SatUShortAccum:
1428 return 4;
1429 case BuiltinType::Accum:
1430 case BuiltinType::UAccum:
1431 case BuiltinType::SatAccum:
1432 case BuiltinType::SatUAccum:
1433 return 5;
1434 case BuiltinType::LongAccum:
1435 case BuiltinType::ULongAccum:
1436 case BuiltinType::SatLongAccum:
1437 case BuiltinType::SatULongAccum:
1438 return 6;
1439 default:
1440 if (BTy->isInteger())
1441 return 0;
1442 llvm_unreachable("Unexpected fixed point or integer type");
1446 /// handleFixedPointConversion - Fixed point operations between fixed
1447 /// point types and integers or other fixed point types do not fall under
1448 /// usual arithmetic conversion since these conversions could result in loss
1449 /// of precsision (N1169 4.1.4). These operations should be calculated with
1450 /// the full precision of their result type (N1169 4.1.6.2.1).
1451 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1452 QualType RHSTy) {
1453 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1454 "Expected at least one of the operands to be a fixed point type");
1455 assert((LHSTy->isFixedPointOrIntegerType() ||
1456 RHSTy->isFixedPointOrIntegerType()) &&
1457 "Special fixed point arithmetic operation conversions are only "
1458 "applied to ints or other fixed point types");
1460 // If one operand has signed fixed-point type and the other operand has
1461 // unsigned fixed-point type, then the unsigned fixed-point operand is
1462 // converted to its corresponding signed fixed-point type and the resulting
1463 // type is the type of the converted operand.
1464 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1465 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1466 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1467 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1469 // The result type is the type with the highest rank, whereby a fixed-point
1470 // conversion rank is always greater than an integer conversion rank; if the
1471 // type of either of the operands is a saturating fixedpoint type, the result
1472 // type shall be the saturating fixed-point type corresponding to the type
1473 // with the highest rank; the resulting value is converted (taking into
1474 // account rounding and overflow) to the precision of the resulting type.
1475 // Same ranks between signed and unsigned types are resolved earlier, so both
1476 // types are either signed or both unsigned at this point.
1477 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1478 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1480 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1482 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1483 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1485 return ResultTy;
1488 /// Check that the usual arithmetic conversions can be performed on this pair of
1489 /// expressions that might be of enumeration type.
1490 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1491 SourceLocation Loc,
1492 Sema::ArithConvKind ACK) {
1493 // C++2a [expr.arith.conv]p1:
1494 // If one operand is of enumeration type and the other operand is of a
1495 // different enumeration type or a floating-point type, this behavior is
1496 // deprecated ([depr.arith.conv.enum]).
1498 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1499 // Eventually we will presumably reject these cases (in C++23 onwards?).
1500 QualType L = LHS->getType(), R = RHS->getType();
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
1512 << L << R;
1513 } else if (!IsCompAssign && LEnum && REnum &&
1514 !S.Context.hasSameUnqualifiedType(L, R)) {
1515 unsigned DiagID;
1516 // In C++ 26, usual arithmetic conversions between 2 different enum types
1517 // are ill-formed.
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;
1540 } else {
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,
1555 SourceLocation Loc,
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())
1562 return QualType();
1565 RHS = UsualUnaryConversions(RHS.get());
1566 if (RHS.isInvalid())
1567 return QualType();
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())
1585 return QualType();
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))
1606 return QualType();
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) {
1645 if (ArgTypes[i])
1646 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1647 else
1648 Types[i] = nullptr;
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),
1656 &ControllingType);
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);
1664 delete [] Types;
1665 return ER;
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
1682 // DR423.
1683 EnterExpressionEvaluationContext Unevaluated(
1684 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1685 ExprResult R = DefaultFunctionArrayLvalueConversion(
1686 reinterpret_cast<Expr *>(ControllingExprOrType));
1687 if (R.isInvalid())
1688 return ExprError();
1689 ControllingExpr = R.get();
1690 } else {
1691 // The extension form uses the type directly rather than converting it.
1692 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1693 if (!ControllingType)
1694 return ExprError();
1697 bool TypeErrorFound = false,
1698 IsResultDependent = ControllingExpr
1699 ? ControllingExpr->isTypeDependent()
1700 : ControllingType->getType()->isDependentType(),
1701 ContainsUnexpandedParameterPack =
1702 ControllingExpr
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;
1717 if (Types[i]) {
1718 if (Types[i]->getType()->containsUnexpandedParameterPack())
1719 ContainsUnexpandedParameterPack = true;
1721 if (Types[i]->getType()->isDependentType()) {
1722 IsResultDependent = true;
1723 } else {
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."
1734 unsigned D = 0;
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
1759 // conversion.
1760 unsigned Reason = 0;
1761 QualType QT = Types[i]->getType();
1762 if (QT->isArrayType())
1763 Reason = 1;
1764 else if (QT.hasQualifiers() &&
1765 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1766 Reason = 2;
1768 if (Reason)
1769 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1770 diag::warn_unreachable_association)
1771 << QT << (Reason - 1);
1774 if (D != 0) {
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;
1801 if (TypeErrorFound)
1802 return ExprError();
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) {
1822 if (!Types[i])
1823 DefaultIndex = 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();
1866 return ExprError();
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;
1876 return ExprError();
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) {
1898 switch (Kind) {
1899 default:
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,
1930 unsigned Offset) {
1931 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1932 S.getLangOpts());
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");
1944 QualType ArgTy[2];
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)
1961 return ExprError();
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)
1975 return ExprError();
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));
1992 return Lit;
1995 std::vector<Token>
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
2001 // parsed yet).
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);
2008 if (!CurrentDecl)
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);
2017 continue;
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)
2023 << Tok.getKind();
2024 SmallString<64> Str;
2025 llvm::raw_svector_ostream OS(Str);
2026 Token &Exp = ExpandedToks.emplace_back();
2027 Exp.startToken();
2028 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2029 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2030 OS << 'L';
2031 Exp.setKind(tok::wide_string_literal);
2032 } else {
2033 Exp.setKind(tok::string_literal);
2035 OS << '"'
2036 << Lexer::Stringify(PredefinedExpr::ComputeName(
2037 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2038 << '"';
2039 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2041 return ExpandedToks;
2044 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
2045 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
2046 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
2047 /// multiple tokens. However, the common case is that StringToks points to one
2048 /// string.
2050 ExprResult
2051 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
2052 assert(!StringToks.empty() && "Must have at least one string!");
2054 // StringToks needs backing storage as it doesn't hold array elements itself
2055 std::vector<Token> ExpandedToks;
2056 if (getLangOpts().MicrosoftExt)
2057 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2059 StringLiteralParser Literal(StringToks, PP);
2060 if (Literal.hadError)
2061 return ExprError();
2063 SmallVector<SourceLocation, 4> StringTokLocs;
2064 for (const Token &Tok : StringToks)
2065 StringTokLocs.push_back(Tok.getLocation());
2067 QualType CharTy = Context.CharTy;
2068 StringLiteralKind Kind = StringLiteralKind::Ordinary;
2069 if (Literal.isWide()) {
2070 CharTy = Context.getWideCharType();
2071 Kind = StringLiteralKind::Wide;
2072 } else if (Literal.isUTF8()) {
2073 if (getLangOpts().Char8)
2074 CharTy = Context.Char8Ty;
2075 Kind = StringLiteralKind::UTF8;
2076 } else if (Literal.isUTF16()) {
2077 CharTy = Context.Char16Ty;
2078 Kind = StringLiteralKind::UTF16;
2079 } else if (Literal.isUTF32()) {
2080 CharTy = Context.Char32Ty;
2081 Kind = StringLiteralKind::UTF32;
2082 } else if (Literal.isPascal()) {
2083 CharTy = Context.UnsignedCharTy;
2086 // Warn on initializing an array of char from a u8 string literal; this
2087 // becomes ill-formed in C++2a.
2088 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
2089 !getLangOpts().Char8 && Kind == StringLiteralKind::UTF8) {
2090 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
2092 // Create removals for all 'u8' prefixes in the string literal(s). This
2093 // ensures C++2a compatibility (but may change the program behavior when
2094 // built by non-Clang compilers for which the execution character set is
2095 // not always UTF-8).
2096 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
2097 SourceLocation RemovalDiagLoc;
2098 for (const Token &Tok : StringToks) {
2099 if (Tok.getKind() == tok::utf8_string_literal) {
2100 if (RemovalDiagLoc.isInvalid())
2101 RemovalDiagLoc = Tok.getLocation();
2102 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
2103 Tok.getLocation(),
2104 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2105 getSourceManager(), getLangOpts())));
2108 Diag(RemovalDiagLoc, RemovalDiag);
2111 QualType StrTy =
2112 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2114 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2115 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2116 Kind, Literal.Pascal, StrTy,
2117 &StringTokLocs[0],
2118 StringTokLocs.size());
2119 if (Literal.getUDSuffix().empty())
2120 return Lit;
2122 // We're building a user-defined literal.
2123 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2124 SourceLocation UDSuffixLoc =
2125 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2126 Literal.getUDSuffixOffset());
2128 // Make sure we're allowed user-defined literals here.
2129 if (!UDLScope)
2130 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2132 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2133 // operator "" X (str, len)
2134 QualType SizeType = Context.getSizeType();
2136 DeclarationName OpName =
2137 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2138 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2139 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2141 QualType ArgTy[] = {
2142 Context.getArrayDecayedType(StrTy), SizeType
2145 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2146 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2147 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2148 /*AllowStringTemplatePack*/ true,
2149 /*DiagnoseMissing*/ true, Lit)) {
2151 case LOLR_Cooked: {
2152 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2153 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2154 StringTokLocs[0]);
2155 Expr *Args[] = { Lit, LenArg };
2157 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2160 case LOLR_Template: {
2161 TemplateArgumentListInfo ExplicitArgs;
2162 TemplateArgument Arg(Lit);
2163 TemplateArgumentLocInfo ArgInfo(Lit);
2164 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2165 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
2166 StringTokLocs.back(), &ExplicitArgs);
2169 case LOLR_StringTemplatePack: {
2170 TemplateArgumentListInfo ExplicitArgs;
2172 unsigned CharBits = Context.getIntWidth(CharTy);
2173 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2174 llvm::APSInt Value(CharBits, CharIsUnsigned);
2176 TemplateArgument TypeArg(CharTy);
2177 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
2178 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2180 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2181 Value = Lit->getCodeUnit(I);
2182 TemplateArgument Arg(Context, Value, CharTy);
2183 TemplateArgumentLocInfo ArgInfo;
2184 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2186 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
2187 StringTokLocs.back(), &ExplicitArgs);
2189 case LOLR_Raw:
2190 case LOLR_ErrorNoDiagnostic:
2191 llvm_unreachable("unexpected literal operator lookup result");
2192 case LOLR_Error:
2193 return ExprError();
2195 llvm_unreachable("unexpected literal operator lookup result");
2198 DeclRefExpr *
2199 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2200 SourceLocation Loc,
2201 const CXXScopeSpec *SS) {
2202 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2203 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2206 DeclRefExpr *
2207 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2208 const DeclarationNameInfo &NameInfo,
2209 const CXXScopeSpec *SS, NamedDecl *FoundD,
2210 SourceLocation TemplateKWLoc,
2211 const TemplateArgumentListInfo *TemplateArgs) {
2212 NestedNameSpecifierLoc NNS =
2213 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
2214 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2215 TemplateArgs);
2218 // CUDA/HIP: Check whether a captured reference variable is referencing a
2219 // host variable in a device or host device lambda.
2220 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
2221 VarDecl *VD) {
2222 if (!S.getLangOpts().CUDA || !VD->hasInit())
2223 return false;
2224 assert(VD->getType()->isReferenceType());
2226 // Check whether the reference variable is referencing a host variable.
2227 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2228 if (!DRE)
2229 return false;
2230 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2231 if (!Referee || !Referee->hasGlobalStorage() ||
2232 Referee->hasAttr<CUDADeviceAttr>())
2233 return false;
2235 // Check whether the current function is a device or host device lambda.
2236 // Check whether the reference variable is a capture by getDeclContext()
2237 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2238 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2239 if (MD && MD->getParent()->isLambda() &&
2240 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2241 VD->getDeclContext() != MD)
2242 return true;
2244 return false;
2247 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2248 // A declaration named in an unevaluated operand never constitutes an odr-use.
2249 if (isUnevaluatedContext())
2250 return NOUR_Unevaluated;
2252 // C++2a [basic.def.odr]p4:
2253 // A variable x whose name appears as a potentially-evaluated expression e
2254 // is odr-used by e unless [...] x is a reference that is usable in
2255 // constant expressions.
2256 // CUDA/HIP:
2257 // If a reference variable referencing a host variable is captured in a
2258 // device or host device lambda, the value of the referee must be copied
2259 // to the capture and the reference variable must be treated as odr-use
2260 // since the value of the referee is not known at compile time and must
2261 // be loaded from the captured.
2262 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2263 if (VD->getType()->isReferenceType() &&
2264 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2265 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2266 VD->isUsableInConstantExpressions(Context))
2267 return NOUR_Constant;
2270 // All remaining non-variable cases constitute an odr-use. For variables, we
2271 // need to wait and see how the expression is used.
2272 return NOUR_None;
2275 /// BuildDeclRefExpr - Build an expression that references a
2276 /// declaration that does not require a closure capture.
2277 DeclRefExpr *
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();
2318 if (FD) {
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());
2331 return E;
2334 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2335 /// possibly a list of template arguments.
2337 /// If this produces template arguments, it is permitted to call
2338 /// DecomposeTemplateName.
2340 /// This actually loses a lot of source location information for
2341 /// non-standard name kinds; we should consider preserving that in
2342 /// some way.
2343 void
2344 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2345 TemplateArgumentListInfo &Buffer,
2346 DeclarationNameInfo &NameInfo,
2347 const TemplateArgumentListInfo *&TemplateArgs) {
2348 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2349 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2350 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2352 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2353 Id.TemplateId->NumArgs);
2354 translateTemplateArguments(TemplateArgsPtr, Buffer);
2356 TemplateName TName = Id.TemplateId->Template.get();
2357 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2358 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2359 TemplateArgs = &Buffer;
2360 } else {
2361 NameInfo = GetNameFromUnqualifiedId(Id);
2362 TemplateArgs = nullptr;
2366 static void emitEmptyLookupTypoDiagnostic(
2367 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2368 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2369 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2370 DeclContext *Ctx =
2371 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2372 if (!TC) {
2373 // Emit a special diagnostic for failed member lookups.
2374 // FIXME: computing the declaration context might fail here (?)
2375 if (Ctx)
2376 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2377 << SS.getRange();
2378 else
2379 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2380 return;
2383 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2384 bool DroppedSpecifier =
2385 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2386 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2387 ? diag::note_implicit_param_decl
2388 : diag::note_previous_decl;
2389 if (!Ctx)
2390 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2391 SemaRef.PDiag(NoteID));
2392 else
2393 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2394 << Typo << Ctx << DroppedSpecifier
2395 << SS.getRange(),
2396 SemaRef.PDiag(NoteID));
2399 /// Diagnose a lookup that found results in an enclosing class during error
2400 /// recovery. This usually indicates that the results were found in a dependent
2401 /// base class that could not be searched as part of a template definition.
2402 /// Always issues a diagnostic (though this may be only a warning in MS
2403 /// compatibility mode).
2405 /// Return \c true if the error is unrecoverable, or \c false if the caller
2406 /// should attempt to recover using these lookup results.
2407 bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) {
2408 // During a default argument instantiation the CurContext points
2409 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2410 // function parameter list, hence add an explicit check.
2411 bool isDefaultArgument =
2412 !CodeSynthesisContexts.empty() &&
2413 CodeSynthesisContexts.back().Kind ==
2414 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2415 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2416 bool isInstance = CurMethod && CurMethod->isInstance() &&
2417 R.getNamingClass() == CurMethod->getParent() &&
2418 !isDefaultArgument;
2420 // There are two ways we can find a class-scope declaration during template
2421 // instantiation that we did not find in the template definition: if it is a
2422 // member of a dependent base class, or if it is declared after the point of
2423 // use in the same class. Distinguish these by comparing the class in which
2424 // the member was found to the naming class of the lookup.
2425 unsigned DiagID = diag::err_found_in_dependent_base;
2426 unsigned NoteID = diag::note_member_declared_at;
2427 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2428 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2429 : diag::err_found_later_in_class;
2430 } else if (getLangOpts().MSVCCompat) {
2431 DiagID = diag::ext_found_in_dependent_base;
2432 NoteID = diag::note_dependent_member_use;
2435 if (isInstance) {
2436 // Give a code modification hint to insert 'this->'.
2437 Diag(R.getNameLoc(), DiagID)
2438 << R.getLookupName()
2439 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2440 CheckCXXThisCapture(R.getNameLoc());
2441 } else {
2442 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2443 // they're not shadowed).
2444 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2447 for (const NamedDecl *D : R)
2448 Diag(D->getLocation(), NoteID);
2450 // Return true if we are inside a default argument instantiation
2451 // and the found name refers to an instance member function, otherwise
2452 // the caller will try to create an implicit member call and this is wrong
2453 // for default arguments.
2455 // FIXME: Is this special case necessary? We could allow the caller to
2456 // diagnose this.
2457 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2458 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2459 return true;
2462 // Tell the callee to try to recover.
2463 return false;
2466 /// Diagnose an empty lookup.
2468 /// \return false if new lookup candidates were found
2469 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2470 CorrectionCandidateCallback &CCC,
2471 TemplateArgumentListInfo *ExplicitTemplateArgs,
2472 ArrayRef<Expr *> Args, TypoExpr **Out) {
2473 DeclarationName Name = R.getLookupName();
2475 unsigned diagnostic = diag::err_undeclared_var_use;
2476 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2477 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2478 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2479 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2480 diagnostic = diag::err_undeclared_use;
2481 diagnostic_suggest = diag::err_undeclared_use_suggest;
2484 // If the original lookup was an unqualified lookup, fake an
2485 // unqualified lookup. This is useful when (for example) the
2486 // original lookup would not have found something because it was a
2487 // dependent name.
2488 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2489 while (DC) {
2490 if (isa<CXXRecordDecl>(DC)) {
2491 LookupQualifiedName(R, DC);
2493 if (!R.empty()) {
2494 // Don't give errors about ambiguities in this lookup.
2495 R.suppressDiagnostics();
2497 // If there's a best viable function among the results, only mention
2498 // that one in the notes.
2499 OverloadCandidateSet Candidates(R.getNameLoc(),
2500 OverloadCandidateSet::CSK_Normal);
2501 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2502 OverloadCandidateSet::iterator Best;
2503 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2504 OR_Success) {
2505 R.clear();
2506 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2507 R.resolveKind();
2510 return DiagnoseDependentMemberLookup(R);
2513 R.clear();
2516 DC = DC->getLookupParent();
2519 // We didn't find anything, so try to correct for a typo.
2520 TypoCorrection Corrected;
2521 if (S && Out) {
2522 SourceLocation TypoLoc = R.getNameLoc();
2523 assert(!ExplicitTemplateArgs &&
2524 "Diagnosing an empty lookup with explicit template args!");
2525 *Out = CorrectTypoDelayed(
2526 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2527 [=](const TypoCorrection &TC) {
2528 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2529 diagnostic, diagnostic_suggest);
2531 nullptr, CTK_ErrorRecovery);
2532 if (*Out)
2533 return true;
2534 } else if (S &&
2535 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2536 S, &SS, CCC, CTK_ErrorRecovery))) {
2537 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2538 bool DroppedSpecifier =
2539 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2540 R.setLookupName(Corrected.getCorrection());
2542 bool AcceptableWithRecovery = false;
2543 bool AcceptableWithoutRecovery = false;
2544 NamedDecl *ND = Corrected.getFoundDecl();
2545 if (ND) {
2546 if (Corrected.isOverloaded()) {
2547 OverloadCandidateSet OCS(R.getNameLoc(),
2548 OverloadCandidateSet::CSK_Normal);
2549 OverloadCandidateSet::iterator Best;
2550 for (NamedDecl *CD : Corrected) {
2551 if (FunctionTemplateDecl *FTD =
2552 dyn_cast<FunctionTemplateDecl>(CD))
2553 AddTemplateOverloadCandidate(
2554 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2555 Args, OCS);
2556 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2557 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2558 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2559 Args, OCS);
2561 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2562 case OR_Success:
2563 ND = Best->FoundDecl;
2564 Corrected.setCorrectionDecl(ND);
2565 break;
2566 default:
2567 // FIXME: Arbitrarily pick the first declaration for the note.
2568 Corrected.setCorrectionDecl(ND);
2569 break;
2572 R.addDecl(ND);
2573 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2574 CXXRecordDecl *Record = nullptr;
2575 if (Corrected.getCorrectionSpecifier()) {
2576 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2577 Record = Ty->getAsCXXRecordDecl();
2579 if (!Record)
2580 Record = cast<CXXRecordDecl>(
2581 ND->getDeclContext()->getRedeclContext());
2582 R.setNamingClass(Record);
2585 auto *UnderlyingND = ND->getUnderlyingDecl();
2586 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2587 isa<FunctionTemplateDecl>(UnderlyingND);
2588 // FIXME: If we ended up with a typo for a type name or
2589 // Objective-C class name, we're in trouble because the parser
2590 // is in the wrong place to recover. Suggest the typo
2591 // correction, but don't make it a fix-it since we're not going
2592 // to recover well anyway.
2593 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2594 getAsTypeTemplateDecl(UnderlyingND) ||
2595 isa<ObjCInterfaceDecl>(UnderlyingND);
2596 } else {
2597 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2598 // because we aren't able to recover.
2599 AcceptableWithoutRecovery = true;
2602 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2603 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2604 ? diag::note_implicit_param_decl
2605 : diag::note_previous_decl;
2606 if (SS.isEmpty())
2607 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2608 PDiag(NoteID), AcceptableWithRecovery);
2609 else
2610 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2611 << Name << computeDeclContext(SS, false)
2612 << DroppedSpecifier << SS.getRange(),
2613 PDiag(NoteID), AcceptableWithRecovery);
2615 // Tell the callee whether to try to recover.
2616 return !AcceptableWithRecovery;
2619 R.clear();
2621 // Emit a special diagnostic for failed member lookups.
2622 // FIXME: computing the declaration context might fail here (?)
2623 if (!SS.isEmpty()) {
2624 Diag(R.getNameLoc(), diag::err_no_member)
2625 << Name << computeDeclContext(SS, false)
2626 << SS.getRange();
2627 return true;
2630 // Give up, we can't recover.
2631 Diag(R.getNameLoc(), diagnostic) << Name;
2632 return true;
2635 /// In Microsoft mode, if we are inside a template class whose parent class has
2636 /// dependent base classes, and we can't resolve an unqualified identifier, then
2637 /// assume the identifier is a member of a dependent base class. We can only
2638 /// recover successfully in static methods, instance methods, and other contexts
2639 /// where 'this' is available. This doesn't precisely match MSVC's
2640 /// instantiation model, but it's close enough.
2641 static Expr *
2642 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2643 DeclarationNameInfo &NameInfo,
2644 SourceLocation TemplateKWLoc,
2645 const TemplateArgumentListInfo *TemplateArgs) {
2646 // Only try to recover from lookup into dependent bases in static methods or
2647 // contexts where 'this' is available.
2648 QualType ThisType = S.getCurrentThisType();
2649 const CXXRecordDecl *RD = nullptr;
2650 if (!ThisType.isNull())
2651 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2652 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2653 RD = MD->getParent();
2654 if (!RD || !RD->hasAnyDependentBases())
2655 return nullptr;
2657 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2658 // is available, suggest inserting 'this->' as a fixit.
2659 SourceLocation Loc = NameInfo.getLoc();
2660 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2661 DB << NameInfo.getName() << RD;
2663 if (!ThisType.isNull()) {
2664 DB << FixItHint::CreateInsertion(Loc, "this->");
2665 return CXXDependentScopeMemberExpr::Create(
2666 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2667 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2668 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2671 // Synthesize a fake NNS that points to the derived class. This will
2672 // perform name lookup during template instantiation.
2673 CXXScopeSpec SS;
2674 auto *NNS =
2675 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2676 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2677 return DependentScopeDeclRefExpr::Create(
2678 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2679 TemplateArgs);
2682 ExprResult
2683 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2684 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2685 bool HasTrailingLParen, bool IsAddressOfOperand,
2686 CorrectionCandidateCallback *CCC,
2687 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2688 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2689 "cannot be direct & operand and have a trailing lparen");
2690 if (SS.isInvalid())
2691 return ExprError();
2693 TemplateArgumentListInfo TemplateArgsBuffer;
2695 // Decompose the UnqualifiedId into the following data.
2696 DeclarationNameInfo NameInfo;
2697 const TemplateArgumentListInfo *TemplateArgs;
2698 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2700 DeclarationName Name = NameInfo.getName();
2701 IdentifierInfo *II = Name.getAsIdentifierInfo();
2702 SourceLocation NameLoc = NameInfo.getLoc();
2704 if (II && II->isEditorPlaceholder()) {
2705 // FIXME: When typed placeholders are supported we can create a typed
2706 // placeholder expression node.
2707 return ExprError();
2710 // C++ [temp.dep.expr]p3:
2711 // An id-expression is type-dependent if it contains:
2712 // -- an identifier that was declared with a dependent type,
2713 // (note: handled after lookup)
2714 // -- a template-id that is dependent,
2715 // (note: handled in BuildTemplateIdExpr)
2716 // -- a conversion-function-id that specifies a dependent type,
2717 // -- a nested-name-specifier that contains a class-name that
2718 // names a dependent type.
2719 // Determine whether this is a member of an unknown specialization;
2720 // we need to handle these differently.
2721 bool DependentID = false;
2722 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2723 Name.getCXXNameType()->isDependentType()) {
2724 DependentID = true;
2725 } else if (SS.isSet()) {
2726 if (DeclContext *DC = computeDeclContext(SS, false)) {
2727 if (RequireCompleteDeclContext(SS, DC))
2728 return ExprError();
2729 } else {
2730 DependentID = true;
2734 if (DependentID)
2735 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2736 IsAddressOfOperand, TemplateArgs);
2738 // Perform the required lookup.
2739 LookupResult R(*this, NameInfo,
2740 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2741 ? LookupObjCImplicitSelfParam
2742 : LookupOrdinaryName);
2743 if (TemplateKWLoc.isValid() || TemplateArgs) {
2744 // Lookup the template name again to correctly establish the context in
2745 // which it was found. This is really unfortunate as we already did the
2746 // lookup to determine that it was a template name in the first place. If
2747 // this becomes a performance hit, we can work harder to preserve those
2748 // results until we get here but it's likely not worth it.
2749 bool MemberOfUnknownSpecialization;
2750 AssumedTemplateKind AssumedTemplate;
2751 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2752 MemberOfUnknownSpecialization, TemplateKWLoc,
2753 &AssumedTemplate))
2754 return ExprError();
2756 if (MemberOfUnknownSpecialization ||
2757 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2758 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2759 IsAddressOfOperand, TemplateArgs);
2760 } else {
2761 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2762 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2764 // If the result might be in a dependent base class, this is a dependent
2765 // id-expression.
2766 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2767 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2768 IsAddressOfOperand, TemplateArgs);
2770 // If this reference is in an Objective-C method, then we need to do
2771 // some special Objective-C lookup, too.
2772 if (IvarLookupFollowUp) {
2773 ExprResult E(LookupInObjCMethod(R, S, II, true));
2774 if (E.isInvalid())
2775 return ExprError();
2777 if (Expr *Ex = E.getAs<Expr>())
2778 return Ex;
2782 if (R.isAmbiguous())
2783 return ExprError();
2785 // This could be an implicitly declared function reference if the language
2786 // mode allows it as a feature.
2787 if (R.empty() && HasTrailingLParen && II &&
2788 getLangOpts().implicitFunctionsAllowed()) {
2789 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2790 if (D) R.addDecl(D);
2793 // Determine whether this name might be a candidate for
2794 // argument-dependent lookup.
2795 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2797 if (R.empty() && !ADL) {
2798 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2799 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2800 TemplateKWLoc, TemplateArgs))
2801 return E;
2804 // Don't diagnose an empty lookup for inline assembly.
2805 if (IsInlineAsmIdentifier)
2806 return ExprError();
2808 // If this name wasn't predeclared and if this is not a function
2809 // call, diagnose the problem.
2810 TypoExpr *TE = nullptr;
2811 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2812 : nullptr);
2813 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2814 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2815 "Typo correction callback misconfigured");
2816 if (CCC) {
2817 // Make sure the callback knows what the typo being diagnosed is.
2818 CCC->setTypoName(II);
2819 if (SS.isValid())
2820 CCC->setTypoNNS(SS.getScopeRep());
2822 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2823 // a template name, but we happen to have always already looked up the name
2824 // before we get here if it must be a template name.
2825 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2826 std::nullopt, &TE)) {
2827 if (TE && KeywordReplacement) {
2828 auto &State = getTypoExprState(TE);
2829 auto BestTC = State.Consumer->getNextCorrection();
2830 if (BestTC.isKeyword()) {
2831 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2832 if (State.DiagHandler)
2833 State.DiagHandler(BestTC);
2834 KeywordReplacement->startToken();
2835 KeywordReplacement->setKind(II->getTokenID());
2836 KeywordReplacement->setIdentifierInfo(II);
2837 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2838 // Clean up the state associated with the TypoExpr, since it has
2839 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2840 clearDelayedTypo(TE);
2841 // Signal that a correction to a keyword was performed by returning a
2842 // valid-but-null ExprResult.
2843 return (Expr*)nullptr;
2845 State.Consumer->resetCorrectionStream();
2847 return TE ? TE : ExprError();
2850 assert(!R.empty() &&
2851 "DiagnoseEmptyLookup returned false but added no results");
2853 // If we found an Objective-C instance variable, let
2854 // LookupInObjCMethod build the appropriate expression to
2855 // reference the ivar.
2856 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2857 R.clear();
2858 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2859 // In a hopelessly buggy code, Objective-C instance variable
2860 // lookup fails and no expression will be built to reference it.
2861 if (!E.isInvalid() && !E.get())
2862 return ExprError();
2863 return E;
2867 // This is guaranteed from this point on.
2868 assert(!R.empty() || ADL);
2870 // Check whether this might be a C++ implicit instance member access.
2871 // C++ [class.mfct.non-static]p3:
2872 // When an id-expression that is not part of a class member access
2873 // syntax and not used to form a pointer to member is used in the
2874 // body of a non-static member function of class X, if name lookup
2875 // resolves the name in the id-expression to a non-static non-type
2876 // member of some class C, the id-expression is transformed into a
2877 // class member access expression using (*this) as the
2878 // postfix-expression to the left of the . operator.
2880 // But we don't actually need to do this for '&' operands if R
2881 // resolved to a function or overloaded function set, because the
2882 // expression is ill-formed if it actually works out to be a
2883 // non-static member function:
2885 // C++ [expr.ref]p4:
2886 // Otherwise, if E1.E2 refers to a non-static member function. . .
2887 // [t]he expression can be used only as the left-hand operand of a
2888 // member function call.
2890 // There are other safeguards against such uses, but it's important
2891 // to get this right here so that we don't end up making a
2892 // spuriously dependent expression if we're inside a dependent
2893 // instance method.
2894 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2895 bool MightBeImplicitMember;
2896 if (!IsAddressOfOperand)
2897 MightBeImplicitMember = true;
2898 else if (!SS.isEmpty())
2899 MightBeImplicitMember = false;
2900 else if (R.isOverloadedResult())
2901 MightBeImplicitMember = false;
2902 else if (R.isUnresolvableResult())
2903 MightBeImplicitMember = true;
2904 else
2905 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2906 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2907 isa<MSPropertyDecl>(R.getFoundDecl());
2909 if (MightBeImplicitMember)
2910 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2911 R, TemplateArgs, S);
2914 if (TemplateArgs || TemplateKWLoc.isValid()) {
2916 // In C++1y, if this is a variable template id, then check it
2917 // in BuildTemplateIdExpr().
2918 // The single lookup result must be a variable template declaration.
2919 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2920 Id.TemplateId->Kind == TNK_Var_template) {
2921 assert(R.getAsSingle<VarTemplateDecl>() &&
2922 "There should only be one declaration found.");
2925 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2928 return BuildDeclarationNameExpr(SS, R, ADL);
2931 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2932 /// declaration name, generally during template instantiation.
2933 /// There's a large number of things which don't need to be done along
2934 /// this path.
2935 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2936 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2937 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2938 if (NameInfo.getName().isDependentName())
2939 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2940 NameInfo, /*TemplateArgs=*/nullptr);
2942 DeclContext *DC = computeDeclContext(SS, false);
2943 if (!DC)
2944 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2945 NameInfo, /*TemplateArgs=*/nullptr);
2947 if (RequireCompleteDeclContext(SS, DC))
2948 return ExprError();
2950 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2951 LookupQualifiedName(R, DC);
2953 if (R.isAmbiguous())
2954 return ExprError();
2956 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2957 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2958 NameInfo, /*TemplateArgs=*/nullptr);
2960 if (R.empty()) {
2961 // Don't diagnose problems with invalid record decl, the secondary no_member
2962 // diagnostic during template instantiation is likely bogus, e.g. if a class
2963 // is invalid because it's derived from an invalid base class, then missing
2964 // members were likely supposed to be inherited.
2965 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2966 if (CD->isInvalidDecl())
2967 return ExprError();
2968 Diag(NameInfo.getLoc(), diag::err_no_member)
2969 << NameInfo.getName() << DC << SS.getRange();
2970 return ExprError();
2973 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2974 // Diagnose a missing typename if this resolved unambiguously to a type in
2975 // a dependent context. If we can recover with a type, downgrade this to
2976 // a warning in Microsoft compatibility mode.
2977 unsigned DiagID = diag::err_typename_missing;
2978 if (RecoveryTSI && getLangOpts().MSVCCompat)
2979 DiagID = diag::ext_typename_missing;
2980 SourceLocation Loc = SS.getBeginLoc();
2981 auto D = Diag(Loc, DiagID);
2982 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2983 << SourceRange(Loc, NameInfo.getEndLoc());
2985 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2986 // context.
2987 if (!RecoveryTSI)
2988 return ExprError();
2990 // Only issue the fixit if we're prepared to recover.
2991 D << FixItHint::CreateInsertion(Loc, "typename ");
2993 // Recover by pretending this was an elaborated type.
2994 QualType Ty = Context.getTypeDeclType(TD);
2995 TypeLocBuilder TLB;
2996 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2998 QualType ET = getElaboratedType(ElaboratedTypeKeyword::None, SS, Ty);
2999 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
3000 QTL.setElaboratedKeywordLoc(SourceLocation());
3001 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
3003 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
3005 return ExprEmpty();
3008 // Defend against this resolving to an implicit member access. We usually
3009 // won't get here if this might be a legitimate a class member (we end up in
3010 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
3011 // a pointer-to-member or in an unevaluated context in C++11.
3012 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
3013 return BuildPossibleImplicitMemberExpr(SS,
3014 /*TemplateKWLoc=*/SourceLocation(),
3015 R, /*TemplateArgs=*/nullptr, S);
3017 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
3020 /// The parser has read a name in, and Sema has detected that we're currently
3021 /// inside an ObjC method. Perform some additional checks and determine if we
3022 /// should form a reference to an ivar.
3024 /// Ideally, most of this would be done by lookup, but there's
3025 /// actually quite a lot of extra work involved.
3026 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
3027 IdentifierInfo *II) {
3028 SourceLocation Loc = Lookup.getNameLoc();
3029 ObjCMethodDecl *CurMethod = getCurMethodDecl();
3031 // Check for error condition which is already reported.
3032 if (!CurMethod)
3033 return DeclResult(true);
3035 // There are two cases to handle here. 1) scoped lookup could have failed,
3036 // in which case we should look for an ivar. 2) scoped lookup could have
3037 // found a decl, but that decl is outside the current instance method (i.e.
3038 // a global variable). In these two cases, we do a lookup for an ivar with
3039 // this name, if the lookup sucedes, we replace it our current decl.
3041 // If we're in a class method, we don't normally want to look for
3042 // ivars. But if we don't find anything else, and there's an
3043 // ivar, that's an error.
3044 bool IsClassMethod = CurMethod->isClassMethod();
3046 bool LookForIvars;
3047 if (Lookup.empty())
3048 LookForIvars = true;
3049 else if (IsClassMethod)
3050 LookForIvars = false;
3051 else
3052 LookForIvars = (Lookup.isSingleResult() &&
3053 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
3054 ObjCInterfaceDecl *IFace = nullptr;
3055 if (LookForIvars) {
3056 IFace = CurMethod->getClassInterface();
3057 ObjCInterfaceDecl *ClassDeclared;
3058 ObjCIvarDecl *IV = nullptr;
3059 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
3060 // Diagnose using an ivar in a class method.
3061 if (IsClassMethod) {
3062 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
3063 return DeclResult(true);
3066 // Diagnose the use of an ivar outside of the declaring class.
3067 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
3068 !declaresSameEntity(ClassDeclared, IFace) &&
3069 !getLangOpts().DebuggerSupport)
3070 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
3072 // Success.
3073 return IV;
3075 } else if (CurMethod->isInstanceMethod()) {
3076 // We should warn if a local variable hides an ivar.
3077 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
3078 ObjCInterfaceDecl *ClassDeclared;
3079 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
3080 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
3081 declaresSameEntity(IFace, ClassDeclared))
3082 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
3085 } else if (Lookup.isSingleResult() &&
3086 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
3087 // If accessing a stand-alone ivar in a class method, this is an error.
3088 if (const ObjCIvarDecl *IV =
3089 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
3090 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
3091 return DeclResult(true);
3095 // Didn't encounter an error, didn't find an ivar.
3096 return DeclResult(false);
3099 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
3100 ObjCIvarDecl *IV) {
3101 ObjCMethodDecl *CurMethod = getCurMethodDecl();
3102 assert(CurMethod && CurMethod->isInstanceMethod() &&
3103 "should not reference ivar from this context");
3105 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
3106 assert(IFace && "should not reference ivar from this context");
3108 // If we're referencing an invalid decl, just return this as a silent
3109 // error node. The error diagnostic was already emitted on the decl.
3110 if (IV->isInvalidDecl())
3111 return ExprError();
3113 // Check if referencing a field with __attribute__((deprecated)).
3114 if (DiagnoseUseOfDecl(IV, Loc))
3115 return ExprError();
3117 // FIXME: This should use a new expr for a direct reference, don't
3118 // turn this into Self->ivar, just return a BareIVarExpr or something.
3119 IdentifierInfo &II = Context.Idents.get("self");
3120 UnqualifiedId SelfName;
3121 SelfName.setImplicitSelfParam(&II);
3122 CXXScopeSpec SelfScopeSpec;
3123 SourceLocation TemplateKWLoc;
3124 ExprResult SelfExpr =
3125 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
3126 /*HasTrailingLParen=*/false,
3127 /*IsAddressOfOperand=*/false);
3128 if (SelfExpr.isInvalid())
3129 return ExprError();
3131 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
3132 if (SelfExpr.isInvalid())
3133 return ExprError();
3135 MarkAnyDeclReferenced(Loc, IV, true);
3137 ObjCMethodFamily MF = CurMethod->getMethodFamily();
3138 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
3139 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
3140 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
3142 ObjCIvarRefExpr *Result = new (Context)
3143 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
3144 IV->getLocation(), SelfExpr.get(), true, true);
3146 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3147 if (!isUnevaluatedContext() &&
3148 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
3149 getCurFunction()->recordUseOfWeak(Result);
3151 if (getLangOpts().ObjCAutoRefCount && !isUnevaluatedContext())
3152 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
3153 ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
3155 return Result;
3158 /// The parser has read a name in, and Sema has detected that we're currently
3159 /// inside an ObjC method. Perform some additional checks and determine if we
3160 /// should form a reference to an ivar. If so, build an expression referencing
3161 /// that ivar.
3162 ExprResult
3163 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
3164 IdentifierInfo *II, bool AllowBuiltinCreation) {
3165 // FIXME: Integrate this lookup step into LookupParsedName.
3166 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
3167 if (Ivar.isInvalid())
3168 return ExprError();
3169 if (Ivar.isUsable())
3170 return BuildIvarRefExpr(S, Lookup.getNameLoc(),
3171 cast<ObjCIvarDecl>(Ivar.get()));
3173 if (Lookup.empty() && II && AllowBuiltinCreation)
3174 LookupBuiltin(Lookup);
3176 // Sentinel value saying that we didn't do anything special.
3177 return ExprResult(false);
3180 /// Cast a base object to a member's actual type.
3182 /// There are two relevant checks:
3184 /// C++ [class.access.base]p7:
3186 /// If a class member access operator [...] is used to access a non-static
3187 /// data member or non-static member function, the reference is ill-formed if
3188 /// the left operand [...] cannot be implicitly converted to a pointer to the
3189 /// naming class of the right operand.
3191 /// C++ [expr.ref]p7:
3193 /// If E2 is a non-static data member or a non-static member function, the
3194 /// program is ill-formed if the class of which E2 is directly a member is an
3195 /// ambiguous base (11.8) of the naming class (11.9.3) of E2.
3197 /// Note that the latter check does not consider access; the access of the
3198 /// "real" base class is checked as appropriate when checking the access of the
3199 /// member name.
3200 ExprResult
3201 Sema::PerformObjectMemberConversion(Expr *From,
3202 NestedNameSpecifier *Qualifier,
3203 NamedDecl *FoundDecl,
3204 NamedDecl *Member) {
3205 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3206 if (!RD)
3207 return From;
3209 QualType DestRecordType;
3210 QualType DestType;
3211 QualType FromRecordType;
3212 QualType FromType = From->getType();
3213 bool PointerConversions = false;
3214 if (isa<FieldDecl>(Member)) {
3215 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
3216 auto FromPtrType = FromType->getAs<PointerType>();
3217 DestRecordType = Context.getAddrSpaceQualType(
3218 DestRecordType, FromPtrType
3219 ? FromType->getPointeeType().getAddressSpace()
3220 : FromType.getAddressSpace());
3222 if (FromPtrType) {
3223 DestType = Context.getPointerType(DestRecordType);
3224 FromRecordType = FromPtrType->getPointeeType();
3225 PointerConversions = true;
3226 } else {
3227 DestType = DestRecordType;
3228 FromRecordType = FromType;
3230 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3231 if (!Method->isImplicitObjectMemberFunction())
3232 return From;
3234 DestType = Method->getThisType().getNonReferenceType();
3235 DestRecordType = Method->getFunctionObjectParameterType();
3237 if (FromType->getAs<PointerType>()) {
3238 FromRecordType = FromType->getPointeeType();
3239 PointerConversions = true;
3240 } else {
3241 FromRecordType = FromType;
3242 DestType = DestRecordType;
3245 LangAS FromAS = FromRecordType.getAddressSpace();
3246 LangAS DestAS = DestRecordType.getAddressSpace();
3247 if (FromAS != DestAS) {
3248 QualType FromRecordTypeWithoutAS =
3249 Context.removeAddrSpaceQualType(FromRecordType);
3250 QualType FromTypeWithDestAS =
3251 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3252 if (PointerConversions)
3253 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3254 From = ImpCastExprToType(From, FromTypeWithDestAS,
3255 CK_AddressSpaceConversion, From->getValueKind())
3256 .get();
3258 } else {
3259 // No conversion necessary.
3260 return From;
3263 if (DestType->isDependentType() || FromType->isDependentType())
3264 return From;
3266 // If the unqualified types are the same, no conversion is necessary.
3267 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3268 return From;
3270 SourceRange FromRange = From->getSourceRange();
3271 SourceLocation FromLoc = FromRange.getBegin();
3273 ExprValueKind VK = From->getValueKind();
3275 // C++ [class.member.lookup]p8:
3276 // [...] Ambiguities can often be resolved by qualifying a name with its
3277 // class name.
3279 // If the member was a qualified name and the qualified referred to a
3280 // specific base subobject type, we'll cast to that intermediate type
3281 // first and then to the object in which the member is declared. That allows
3282 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3284 // class Base { public: int x; };
3285 // class Derived1 : public Base { };
3286 // class Derived2 : public Base { };
3287 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3289 // void VeryDerived::f() {
3290 // x = 17; // error: ambiguous base subobjects
3291 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3292 // }
3293 if (Qualifier && Qualifier->getAsType()) {
3294 QualType QType = QualType(Qualifier->getAsType(), 0);
3295 assert(QType->isRecordType() && "lookup done with non-record type");
3297 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3299 // In C++98, the qualifier type doesn't actually have to be a base
3300 // type of the object type, in which case we just ignore it.
3301 // Otherwise build the appropriate casts.
3302 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3303 CXXCastPath BasePath;
3304 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3305 FromLoc, FromRange, &BasePath))
3306 return ExprError();
3308 if (PointerConversions)
3309 QType = Context.getPointerType(QType);
3310 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3311 VK, &BasePath).get();
3313 FromType = QType;
3314 FromRecordType = QRecordType;
3316 // If the qualifier type was the same as the destination type,
3317 // we're done.
3318 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3319 return From;
3323 CXXCastPath BasePath;
3324 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3325 FromLoc, FromRange, &BasePath,
3326 /*IgnoreAccess=*/true))
3327 return ExprError();
3329 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3330 VK, &BasePath);
3333 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3334 const LookupResult &R,
3335 bool HasTrailingLParen) {
3336 // Only when used directly as the postfix-expression of a call.
3337 if (!HasTrailingLParen)
3338 return false;
3340 // Never if a scope specifier was provided.
3341 if (SS.isSet())
3342 return false;
3344 // Only in C++ or ObjC++.
3345 if (!getLangOpts().CPlusPlus)
3346 return false;
3348 // Turn off ADL when we find certain kinds of declarations during
3349 // normal lookup:
3350 for (const NamedDecl *D : R) {
3351 // C++0x [basic.lookup.argdep]p3:
3352 // -- a declaration of a class member
3353 // Since using decls preserve this property, we check this on the
3354 // original decl.
3355 if (D->isCXXClassMember())
3356 return false;
3358 // C++0x [basic.lookup.argdep]p3:
3359 // -- a block-scope function declaration that is not a
3360 // using-declaration
3361 // NOTE: we also trigger this for function templates (in fact, we
3362 // don't check the decl type at all, since all other decl types
3363 // turn off ADL anyway).
3364 if (isa<UsingShadowDecl>(D))
3365 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3366 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3367 return false;
3369 // C++0x [basic.lookup.argdep]p3:
3370 // -- a declaration that is neither a function or a function
3371 // template
3372 // And also for builtin functions.
3373 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3374 // But also builtin functions.
3375 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3376 return false;
3377 } else if (!isa<FunctionTemplateDecl>(D))
3378 return false;
3381 return true;
3385 /// Diagnoses obvious problems with the use of the given declaration
3386 /// as an expression. This is only actually called for lookups that
3387 /// were not overloaded, and it doesn't promise that the declaration
3388 /// will in fact be used.
3389 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D,
3390 bool AcceptInvalid) {
3391 if (D->isInvalidDecl() && !AcceptInvalid)
3392 return true;
3394 if (isa<TypedefNameDecl>(D)) {
3395 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3396 return true;
3399 if (isa<ObjCInterfaceDecl>(D)) {
3400 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3401 return true;
3404 if (isa<NamespaceDecl>(D)) {
3405 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3406 return true;
3409 return false;
3412 // Certain multiversion types should be treated as overloaded even when there is
3413 // only one result.
3414 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3415 assert(R.isSingleResult() && "Expected only a single result");
3416 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3417 return FD &&
3418 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3421 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3422 LookupResult &R, bool NeedsADL,
3423 bool AcceptInvalidDecl) {
3424 // If this is a single, fully-resolved result and we don't need ADL,
3425 // just build an ordinary singleton decl ref.
3426 if (!NeedsADL && R.isSingleResult() &&
3427 !R.getAsSingle<FunctionTemplateDecl>() &&
3428 !ShouldLookupResultBeMultiVersionOverload(R))
3429 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3430 R.getRepresentativeDecl(), nullptr,
3431 AcceptInvalidDecl);
3433 // We only need to check the declaration if there's exactly one
3434 // result, because in the overloaded case the results can only be
3435 // functions and function templates.
3436 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3437 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3438 AcceptInvalidDecl))
3439 return ExprError();
3441 // Otherwise, just build an unresolved lookup expression. Suppress
3442 // any lookup-related diagnostics; we'll hash these out later, when
3443 // we've picked a target.
3444 R.suppressDiagnostics();
3446 UnresolvedLookupExpr *ULE
3447 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3448 SS.getWithLocInContext(Context),
3449 R.getLookupNameInfo(),
3450 NeedsADL, R.isOverloadedResult(),
3451 R.begin(), R.end());
3453 return ULE;
3456 static void diagnoseUncapturableValueReferenceOrBinding(Sema &S,
3457 SourceLocation loc,
3458 ValueDecl *var);
3460 /// Complete semantic analysis for a reference to the given declaration.
3461 ExprResult Sema::BuildDeclarationNameExpr(
3462 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3463 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3464 bool AcceptInvalidDecl) {
3465 assert(D && "Cannot refer to a NULL declaration");
3466 assert(!isa<FunctionTemplateDecl>(D) &&
3467 "Cannot refer unambiguously to a function template");
3469 SourceLocation Loc = NameInfo.getLoc();
3470 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3471 // Recovery from invalid cases (e.g. D is an invalid Decl).
3472 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3473 // diagnostics, as invalid decls use int as a fallback type.
3474 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3477 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3478 // Specifically diagnose references to class templates that are missing
3479 // a template argument list.
3480 diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3481 return ExprError();
3484 // Make sure that we're referring to a value.
3485 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3486 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3487 Diag(D->getLocation(), diag::note_declared_at);
3488 return ExprError();
3491 // Check whether this declaration can be used. Note that we suppress
3492 // this check when we're going to perform argument-dependent lookup
3493 // on this function name, because this might not be the function
3494 // that overload resolution actually selects.
3495 if (DiagnoseUseOfDecl(D, Loc))
3496 return ExprError();
3498 auto *VD = cast<ValueDecl>(D);
3500 // Only create DeclRefExpr's for valid Decl's.
3501 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3502 return ExprError();
3504 // Handle members of anonymous structs and unions. If we got here,
3505 // and the reference is to a class member indirect field, then this
3506 // must be the subject of a pointer-to-member expression.
3507 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3508 IndirectField && !IndirectField->isCXXClassMember())
3509 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3510 IndirectField);
3512 QualType type = VD->getType();
3513 if (type.isNull())
3514 return ExprError();
3515 ExprValueKind valueKind = VK_PRValue;
3517 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3518 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3519 // is expanded by some outer '...' in the context of the use.
3520 type = type.getNonPackExpansionType();
3522 switch (D->getKind()) {
3523 // Ignore all the non-ValueDecl kinds.
3524 #define ABSTRACT_DECL(kind)
3525 #define VALUE(type, base)
3526 #define DECL(type, base) case Decl::type:
3527 #include "clang/AST/DeclNodes.inc"
3528 llvm_unreachable("invalid value decl kind");
3530 // These shouldn't make it here.
3531 case Decl::ObjCAtDefsField:
3532 llvm_unreachable("forming non-member reference to ivar?");
3534 // Enum constants are always r-values and never references.
3535 // Unresolved using declarations are dependent.
3536 case Decl::EnumConstant:
3537 case Decl::UnresolvedUsingValue:
3538 case Decl::OMPDeclareReduction:
3539 case Decl::OMPDeclareMapper:
3540 valueKind = VK_PRValue;
3541 break;
3543 // Fields and indirect fields that got here must be for
3544 // pointer-to-member expressions; we just call them l-values for
3545 // internal consistency, because this subexpression doesn't really
3546 // exist in the high-level semantics.
3547 case Decl::Field:
3548 case Decl::IndirectField:
3549 case Decl::ObjCIvar:
3550 assert(getLangOpts().CPlusPlus && "building reference to field in C?");
3552 // These can't have reference type in well-formed programs, but
3553 // for internal consistency we do this anyway.
3554 type = type.getNonReferenceType();
3555 valueKind = VK_LValue;
3556 break;
3558 // Non-type template parameters are either l-values or r-values
3559 // depending on the type.
3560 case Decl::NonTypeTemplateParm: {
3561 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3562 type = reftype->getPointeeType();
3563 valueKind = VK_LValue; // even if the parameter is an r-value reference
3564 break;
3567 // [expr.prim.id.unqual]p2:
3568 // If the entity is a template parameter object for a template
3569 // parameter of type T, the type of the expression is const T.
3570 // [...] The expression is an lvalue if the entity is a [...] template
3571 // parameter object.
3572 if (type->isRecordType()) {
3573 type = type.getUnqualifiedType().withConst();
3574 valueKind = VK_LValue;
3575 break;
3578 // For non-references, we need to strip qualifiers just in case
3579 // the template parameter was declared as 'const int' or whatever.
3580 valueKind = VK_PRValue;
3581 type = type.getUnqualifiedType();
3582 break;
3585 case Decl::Var:
3586 case Decl::VarTemplateSpecialization:
3587 case Decl::VarTemplatePartialSpecialization:
3588 case Decl::Decomposition:
3589 case Decl::OMPCapturedExpr:
3590 // In C, "extern void blah;" is valid and is an r-value.
3591 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3592 type->isVoidType()) {
3593 valueKind = VK_PRValue;
3594 break;
3596 [[fallthrough]];
3598 case Decl::ImplicitParam:
3599 case Decl::ParmVar: {
3600 // These are always l-values.
3601 valueKind = VK_LValue;
3602 type = type.getNonReferenceType();
3604 // FIXME: Does the addition of const really only apply in
3605 // potentially-evaluated contexts? Since the variable isn't actually
3606 // captured in an unevaluated context, it seems that the answer is no.
3607 if (!isUnevaluatedContext()) {
3608 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3609 if (!CapturedType.isNull())
3610 type = CapturedType;
3613 break;
3616 case Decl::Binding:
3617 // These are always lvalues.
3618 valueKind = VK_LValue;
3619 type = type.getNonReferenceType();
3620 break;
3622 case Decl::Function: {
3623 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3624 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3625 type = Context.BuiltinFnTy;
3626 valueKind = VK_PRValue;
3627 break;
3631 const FunctionType *fty = type->castAs<FunctionType>();
3633 // If we're referring to a function with an __unknown_anytype
3634 // result type, make the entire expression __unknown_anytype.
3635 if (fty->getReturnType() == Context.UnknownAnyTy) {
3636 type = Context.UnknownAnyTy;
3637 valueKind = VK_PRValue;
3638 break;
3641 // Functions are l-values in C++.
3642 if (getLangOpts().CPlusPlus) {
3643 valueKind = VK_LValue;
3644 break;
3647 // C99 DR 316 says that, if a function type comes from a
3648 // function definition (without a prototype), that type is only
3649 // used for checking compatibility. Therefore, when referencing
3650 // the function, we pretend that we don't have the full function
3651 // type.
3652 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3653 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3654 fty->getExtInfo());
3656 // Functions are r-values in C.
3657 valueKind = VK_PRValue;
3658 break;
3661 case Decl::CXXDeductionGuide:
3662 llvm_unreachable("building reference to deduction guide");
3664 case Decl::MSProperty:
3665 case Decl::MSGuid:
3666 case Decl::TemplateParamObject:
3667 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3668 // capture in OpenMP, or duplicated between host and device?
3669 valueKind = VK_LValue;
3670 break;
3672 case Decl::UnnamedGlobalConstant:
3673 valueKind = VK_LValue;
3674 break;
3676 case Decl::CXXMethod:
3677 // If we're referring to a method with an __unknown_anytype
3678 // result type, make the entire expression __unknown_anytype.
3679 // This should only be possible with a type written directly.
3680 if (const FunctionProtoType *proto =
3681 dyn_cast<FunctionProtoType>(VD->getType()))
3682 if (proto->getReturnType() == Context.UnknownAnyTy) {
3683 type = Context.UnknownAnyTy;
3684 valueKind = VK_PRValue;
3685 break;
3688 // C++ methods are l-values if static, r-values if non-static.
3689 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3690 valueKind = VK_LValue;
3691 break;
3693 [[fallthrough]];
3695 case Decl::CXXConversion:
3696 case Decl::CXXDestructor:
3697 case Decl::CXXConstructor:
3698 valueKind = VK_PRValue;
3699 break;
3702 auto *E =
3703 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3704 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3705 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3706 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3707 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3708 // diagnostics).
3709 if (VD->isInvalidDecl() && E)
3710 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3711 return E;
3714 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3715 SmallString<32> &Target) {
3716 Target.resize(CharByteWidth * (Source.size() + 1));
3717 char *ResultPtr = &Target[0];
3718 const llvm::UTF8 *ErrorPtr;
3719 bool success =
3720 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3721 (void)success;
3722 assert(success);
3723 Target.resize(ResultPtr - &Target[0]);
3726 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3727 PredefinedIdentKind IK) {
3728 Decl *currentDecl = getPredefinedExprDecl(CurContext);
3729 if (!currentDecl) {
3730 Diag(Loc, diag::ext_predef_outside_function);
3731 currentDecl = Context.getTranslationUnitDecl();
3734 QualType ResTy;
3735 StringLiteral *SL = nullptr;
3736 if (cast<DeclContext>(currentDecl)->isDependentContext())
3737 ResTy = Context.DependentTy;
3738 else {
3739 // Pre-defined identifiers are of type char[x], where x is the length of
3740 // the string.
3741 auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3742 unsigned Length = Str.length();
3744 llvm::APInt LengthI(32, Length + 1);
3745 if (IK == PredefinedIdentKind::LFunction ||
3746 IK == PredefinedIdentKind::LFuncSig) {
3747 ResTy =
3748 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3749 SmallString<32> RawChars;
3750 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3751 Str, RawChars);
3752 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3753 ArraySizeModifier::Normal,
3754 /*IndexTypeQuals*/ 0);
3755 SL = StringLiteral::Create(Context, RawChars, StringLiteralKind::Wide,
3756 /*Pascal*/ false, ResTy, Loc);
3757 } else {
3758 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3759 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3760 ArraySizeModifier::Normal,
3761 /*IndexTypeQuals*/ 0);
3762 SL = StringLiteral::Create(Context, Str, StringLiteralKind::Ordinary,
3763 /*Pascal*/ false, ResTy, Loc);
3767 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3768 SL);
3771 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3772 SourceLocation LParen,
3773 SourceLocation RParen,
3774 TypeSourceInfo *TSI) {
3775 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3778 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3779 SourceLocation LParen,
3780 SourceLocation RParen,
3781 ParsedType ParsedTy) {
3782 TypeSourceInfo *TSI = nullptr;
3783 QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3785 if (Ty.isNull())
3786 return ExprError();
3787 if (!TSI)
3788 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3790 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3793 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3794 return BuildPredefinedExpr(Loc, getPredefinedExprKind(Kind));
3797 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3798 SmallString<16> CharBuffer;
3799 bool Invalid = false;
3800 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3801 if (Invalid)
3802 return ExprError();
3804 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3805 PP, Tok.getKind());
3806 if (Literal.hadError())
3807 return ExprError();
3809 QualType Ty;
3810 if (Literal.isWide())
3811 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3812 else if (Literal.isUTF8() && getLangOpts().C23)
3813 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3814 else if (Literal.isUTF8() && getLangOpts().Char8)
3815 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3816 else if (Literal.isUTF16())
3817 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3818 else if (Literal.isUTF32())
3819 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3820 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3821 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3822 else
3823 Ty = Context.CharTy; // 'x' -> char in C++;
3824 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3826 CharacterLiteralKind Kind = CharacterLiteralKind::Ascii;
3827 if (Literal.isWide())
3828 Kind = CharacterLiteralKind::Wide;
3829 else if (Literal.isUTF16())
3830 Kind = CharacterLiteralKind::UTF16;
3831 else if (Literal.isUTF32())
3832 Kind = CharacterLiteralKind::UTF32;
3833 else if (Literal.isUTF8())
3834 Kind = CharacterLiteralKind::UTF8;
3836 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3837 Tok.getLocation());
3839 if (Literal.getUDSuffix().empty())
3840 return Lit;
3842 // We're building a user-defined literal.
3843 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3844 SourceLocation UDSuffixLoc =
3845 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3847 // Make sure we're allowed user-defined literals here.
3848 if (!UDLScope)
3849 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3851 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3852 // operator "" X (ch)
3853 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3854 Lit, Tok.getLocation());
3857 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3858 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3859 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3860 Context.IntTy, Loc);
3863 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3864 QualType Ty, SourceLocation Loc) {
3865 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3867 using llvm::APFloat;
3868 APFloat Val(Format);
3870 APFloat::opStatus result = Literal.GetFloatValue(Val);
3872 // Overflow is always an error, but underflow is only an error if
3873 // we underflowed to zero (APFloat reports denormals as underflow).
3874 if ((result & APFloat::opOverflow) ||
3875 ((result & APFloat::opUnderflow) && Val.isZero())) {
3876 unsigned diagnostic;
3877 SmallString<20> buffer;
3878 if (result & APFloat::opOverflow) {
3879 diagnostic = diag::warn_float_overflow;
3880 APFloat::getLargest(Format).toString(buffer);
3881 } else {
3882 diagnostic = diag::warn_float_underflow;
3883 APFloat::getSmallest(Format).toString(buffer);
3886 S.Diag(Loc, diagnostic)
3887 << Ty
3888 << StringRef(buffer.data(), buffer.size());
3891 bool isExact = (result == APFloat::opOK);
3892 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3895 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3896 assert(E && "Invalid expression");
3898 if (E->isValueDependent())
3899 return false;
3901 QualType QT = E->getType();
3902 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3903 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3904 return true;
3907 llvm::APSInt ValueAPS;
3908 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3910 if (R.isInvalid())
3911 return true;
3913 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3914 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3915 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3916 << toString(ValueAPS, 10) << ValueIsPositive;
3917 return true;
3920 return false;
3923 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3924 // Fast path for a single digit (which is quite common). A single digit
3925 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3926 if (Tok.getLength() == 1) {
3927 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3928 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3931 SmallString<128> SpellingBuffer;
3932 // NumericLiteralParser wants to overread by one character. Add padding to
3933 // the buffer in case the token is copied to the buffer. If getSpelling()
3934 // returns a StringRef to the memory buffer, it should have a null char at
3935 // the EOF, so it is also safe.
3936 SpellingBuffer.resize(Tok.getLength() + 1);
3938 // Get the spelling of the token, which eliminates trigraphs, etc.
3939 bool Invalid = false;
3940 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3941 if (Invalid)
3942 return ExprError();
3944 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3945 PP.getSourceManager(), PP.getLangOpts(),
3946 PP.getTargetInfo(), PP.getDiagnostics());
3947 if (Literal.hadError)
3948 return ExprError();
3950 if (Literal.hasUDSuffix()) {
3951 // We're building a user-defined literal.
3952 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3953 SourceLocation UDSuffixLoc =
3954 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3956 // Make sure we're allowed user-defined literals here.
3957 if (!UDLScope)
3958 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3960 QualType CookedTy;
3961 if (Literal.isFloatingLiteral()) {
3962 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3963 // long double, the literal is treated as a call of the form
3964 // operator "" X (f L)
3965 CookedTy = Context.LongDoubleTy;
3966 } else {
3967 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3968 // unsigned long long, the literal is treated as a call of the form
3969 // operator "" X (n ULL)
3970 CookedTy = Context.UnsignedLongLongTy;
3973 DeclarationName OpName =
3974 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3975 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3976 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3978 SourceLocation TokLoc = Tok.getLocation();
3980 // Perform literal operator lookup to determine if we're building a raw
3981 // literal or a cooked one.
3982 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3983 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3984 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3985 /*AllowStringTemplatePack*/ false,
3986 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3987 case LOLR_ErrorNoDiagnostic:
3988 // Lookup failure for imaginary constants isn't fatal, there's still the
3989 // GNU extension producing _Complex types.
3990 break;
3991 case LOLR_Error:
3992 return ExprError();
3993 case LOLR_Cooked: {
3994 Expr *Lit;
3995 if (Literal.isFloatingLiteral()) {
3996 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3997 } else {
3998 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3999 if (Literal.GetIntegerValue(ResultVal))
4000 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4001 << /* Unsigned */ 1;
4002 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
4003 Tok.getLocation());
4005 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
4008 case LOLR_Raw: {
4009 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
4010 // literal is treated as a call of the form
4011 // operator "" X ("n")
4012 unsigned Length = Literal.getUDSuffixOffset();
4013 QualType StrTy = Context.getConstantArrayType(
4014 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
4015 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
4016 Expr *Lit =
4017 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
4018 StringLiteralKind::Ordinary,
4019 /*Pascal*/ false, StrTy, &TokLoc, 1);
4020 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
4023 case LOLR_Template: {
4024 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
4025 // template), L is treated as a call fo the form
4026 // operator "" X <'c1', 'c2', ... 'ck'>()
4027 // where n is the source character sequence c1 c2 ... ck.
4028 TemplateArgumentListInfo ExplicitArgs;
4029 unsigned CharBits = Context.getIntWidth(Context.CharTy);
4030 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
4031 llvm::APSInt Value(CharBits, CharIsUnsigned);
4032 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
4033 Value = TokSpelling[I];
4034 TemplateArgument Arg(Context, Value, Context.CharTy);
4035 TemplateArgumentLocInfo ArgInfo;
4036 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
4038 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, TokLoc,
4039 &ExplicitArgs);
4041 case LOLR_StringTemplatePack:
4042 llvm_unreachable("unexpected literal operator lookup result");
4046 Expr *Res;
4048 if (Literal.isFixedPointLiteral()) {
4049 QualType Ty;
4051 if (Literal.isAccum) {
4052 if (Literal.isHalf) {
4053 Ty = Context.ShortAccumTy;
4054 } else if (Literal.isLong) {
4055 Ty = Context.LongAccumTy;
4056 } else {
4057 Ty = Context.AccumTy;
4059 } else if (Literal.isFract) {
4060 if (Literal.isHalf) {
4061 Ty = Context.ShortFractTy;
4062 } else if (Literal.isLong) {
4063 Ty = Context.LongFractTy;
4064 } else {
4065 Ty = Context.FractTy;
4069 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
4071 bool isSigned = !Literal.isUnsigned;
4072 unsigned scale = Context.getFixedPointScale(Ty);
4073 unsigned bit_width = Context.getTypeInfo(Ty).Width;
4075 llvm::APInt Val(bit_width, 0, isSigned);
4076 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
4077 bool ValIsZero = Val.isZero() && !Overflowed;
4079 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
4080 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
4081 // Clause 6.4.4 - The value of a constant shall be in the range of
4082 // representable values for its type, with exception for constants of a
4083 // fract type with a value of exactly 1; such a constant shall denote
4084 // the maximal value for the type.
4085 --Val;
4086 else if (Val.ugt(MaxVal) || Overflowed)
4087 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
4089 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
4090 Tok.getLocation(), scale);
4091 } else if (Literal.isFloatingLiteral()) {
4092 QualType Ty;
4093 if (Literal.isHalf){
4094 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
4095 Ty = Context.HalfTy;
4096 else {
4097 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
4098 return ExprError();
4100 } else if (Literal.isFloat)
4101 Ty = Context.FloatTy;
4102 else if (Literal.isLong)
4103 Ty = Context.LongDoubleTy;
4104 else if (Literal.isFloat16)
4105 Ty = Context.Float16Ty;
4106 else if (Literal.isFloat128)
4107 Ty = Context.Float128Ty;
4108 else
4109 Ty = Context.DoubleTy;
4111 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
4113 if (Ty == Context.DoubleTy) {
4114 if (getLangOpts().SinglePrecisionConstants) {
4115 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4116 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4118 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4119 "cl_khr_fp64", getLangOpts())) {
4120 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4121 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
4122 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
4123 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4126 } else if (!Literal.isIntegerLiteral()) {
4127 return ExprError();
4128 } else {
4129 QualType Ty;
4131 // 'z/uz' literals are a C++23 feature.
4132 if (Literal.isSizeT)
4133 Diag(Tok.getLocation(), getLangOpts().CPlusPlus
4134 ? getLangOpts().CPlusPlus23
4135 ? diag::warn_cxx20_compat_size_t_suffix
4136 : diag::ext_cxx23_size_t_suffix
4137 : diag::err_cxx23_size_t_suffix);
4139 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4140 // but we do not currently support the suffix in C++ mode because it's not
4141 // entirely clear whether WG21 will prefer this suffix to return a library
4142 // type such as std::bit_int instead of returning a _BitInt.
4143 if (Literal.isBitInt && !getLangOpts().CPlusPlus)
4144 PP.Diag(Tok.getLocation(), getLangOpts().C23
4145 ? diag::warn_c23_compat_bitint_suffix
4146 : diag::ext_c23_bitint_suffix);
4148 // Get the value in the widest-possible width. What is "widest" depends on
4149 // whether the literal is a bit-precise integer or not. For a bit-precise
4150 // integer type, try to scan the source to determine how many bits are
4151 // needed to represent the value. This may seem a bit expensive, but trying
4152 // to get the integer value from an overly-wide APInt is *extremely*
4153 // expensive, so the naive approach of assuming
4154 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4155 unsigned BitsNeeded =
4156 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
4157 Literal.getLiteralDigits(), Literal.getRadix())
4158 : Context.getTargetInfo().getIntMaxTWidth();
4159 llvm::APInt ResultVal(BitsNeeded, 0);
4161 if (Literal.GetIntegerValue(ResultVal)) {
4162 // If this value didn't fit into uintmax_t, error and force to ull.
4163 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4164 << /* Unsigned */ 1;
4165 Ty = Context.UnsignedLongLongTy;
4166 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4167 "long long is not intmax_t?");
4168 } else {
4169 // If this value fits into a ULL, try to figure out what else it fits into
4170 // according to the rules of C99 6.4.4.1p5.
4172 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4173 // be an unsigned int.
4174 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4176 // Check from smallest to largest, picking the smallest type we can.
4177 unsigned Width = 0;
4179 // Microsoft specific integer suffixes are explicitly sized.
4180 if (Literal.MicrosoftInteger) {
4181 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4182 Width = 8;
4183 Ty = Context.CharTy;
4184 } else {
4185 Width = Literal.MicrosoftInteger;
4186 Ty = Context.getIntTypeForBitwidth(Width,
4187 /*Signed=*/!Literal.isUnsigned);
4191 // Bit-precise integer literals are automagically-sized based on the
4192 // width required by the literal.
4193 if (Literal.isBitInt) {
4194 // The signed version has one more bit for the sign value. There are no
4195 // zero-width bit-precise integers, even if the literal value is 0.
4196 Width = std::max(ResultVal.getActiveBits(), 1u) +
4197 (Literal.isUnsigned ? 0u : 1u);
4199 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4200 // and reset the type to the largest supported width.
4201 unsigned int MaxBitIntWidth =
4202 Context.getTargetInfo().getMaxBitIntWidth();
4203 if (Width > MaxBitIntWidth) {
4204 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4205 << Literal.isUnsigned;
4206 Width = MaxBitIntWidth;
4209 // Reset the result value to the smaller APInt and select the correct
4210 // type to be used. Note, we zext even for signed values because the
4211 // literal itself is always an unsigned value (a preceeding - is a
4212 // unary operator, not part of the literal).
4213 ResultVal = ResultVal.zextOrTrunc(Width);
4214 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4217 // Check C++23 size_t literals.
4218 if (Literal.isSizeT) {
4219 assert(!Literal.MicrosoftInteger &&
4220 "size_t literals can't be Microsoft literals");
4221 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4222 Context.getTargetInfo().getSizeType());
4224 // Does it fit in size_t?
4225 if (ResultVal.isIntN(SizeTSize)) {
4226 // Does it fit in ssize_t?
4227 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4228 Ty = Context.getSignedSizeType();
4229 else if (AllowUnsigned)
4230 Ty = Context.getSizeType();
4231 Width = SizeTSize;
4235 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4236 !Literal.isSizeT) {
4237 // Are int/unsigned possibilities?
4238 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4240 // Does it fit in a unsigned int?
4241 if (ResultVal.isIntN(IntSize)) {
4242 // Does it fit in a signed int?
4243 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4244 Ty = Context.IntTy;
4245 else if (AllowUnsigned)
4246 Ty = Context.UnsignedIntTy;
4247 Width = IntSize;
4251 // Are long/unsigned long possibilities?
4252 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4253 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4255 // Does it fit in a unsigned long?
4256 if (ResultVal.isIntN(LongSize)) {
4257 // Does it fit in a signed long?
4258 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4259 Ty = Context.LongTy;
4260 else if (AllowUnsigned)
4261 Ty = Context.UnsignedLongTy;
4262 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4263 // is compatible.
4264 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4265 const unsigned LongLongSize =
4266 Context.getTargetInfo().getLongLongWidth();
4267 Diag(Tok.getLocation(),
4268 getLangOpts().CPlusPlus
4269 ? Literal.isLong
4270 ? diag::warn_old_implicitly_unsigned_long_cxx
4271 : /*C++98 UB*/ diag::
4272 ext_old_implicitly_unsigned_long_cxx
4273 : diag::warn_old_implicitly_unsigned_long)
4274 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4275 : /*will be ill-formed*/ 1);
4276 Ty = Context.UnsignedLongTy;
4278 Width = LongSize;
4282 // Check long long if needed.
4283 if (Ty.isNull() && !Literal.isSizeT) {
4284 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4286 // Does it fit in a unsigned long long?
4287 if (ResultVal.isIntN(LongLongSize)) {
4288 // Does it fit in a signed long long?
4289 // To be compatible with MSVC, hex integer literals ending with the
4290 // LL or i64 suffix are always signed in Microsoft mode.
4291 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4292 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4293 Ty = Context.LongLongTy;
4294 else if (AllowUnsigned)
4295 Ty = Context.UnsignedLongLongTy;
4296 Width = LongLongSize;
4298 // 'long long' is a C99 or C++11 feature, whether the literal
4299 // explicitly specified 'long long' or we needed the extra width.
4300 if (getLangOpts().CPlusPlus)
4301 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4302 ? diag::warn_cxx98_compat_longlong
4303 : diag::ext_cxx11_longlong);
4304 else if (!getLangOpts().C99)
4305 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4309 // If we still couldn't decide a type, we either have 'size_t' literal
4310 // that is out of range, or a decimal literal that does not fit in a
4311 // signed long long and has no U suffix.
4312 if (Ty.isNull()) {
4313 if (Literal.isSizeT)
4314 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4315 << Literal.isUnsigned;
4316 else
4317 Diag(Tok.getLocation(),
4318 diag::ext_integer_literal_too_large_for_signed);
4319 Ty = Context.UnsignedLongLongTy;
4320 Width = Context.getTargetInfo().getLongLongWidth();
4323 if (ResultVal.getBitWidth() != Width)
4324 ResultVal = ResultVal.trunc(Width);
4326 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4329 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4330 if (Literal.isImaginary) {
4331 Res = new (Context) ImaginaryLiteral(Res,
4332 Context.getComplexType(Res->getType()));
4334 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4336 return Res;
4339 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4340 assert(E && "ActOnParenExpr() missing expr");
4341 QualType ExprTy = E->getType();
4342 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4343 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4344 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4345 return new (Context) ParenExpr(L, R, E);
4348 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4349 SourceLocation Loc,
4350 SourceRange ArgRange) {
4351 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4352 // scalar or vector data type argument..."
4353 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4354 // type (C99 6.2.5p18) or void.
4355 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4356 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4357 << T << ArgRange;
4358 return true;
4361 assert((T->isVoidType() || !T->isIncompleteType()) &&
4362 "Scalar types should always be complete");
4363 return false;
4366 static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T,
4367 SourceLocation Loc,
4368 SourceRange ArgRange) {
4369 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4370 if (!T->isVectorType() && !T->isSizelessVectorType())
4371 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4372 << ""
4373 << "__builtin_vectorelements" << T << ArgRange;
4375 return false;
4378 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4379 SourceLocation Loc,
4380 SourceRange ArgRange,
4381 UnaryExprOrTypeTrait TraitKind) {
4382 // Invalid types must be hard errors for SFINAE in C++.
4383 if (S.LangOpts.CPlusPlus)
4384 return true;
4386 // C99 6.5.3.4p1:
4387 if (T->isFunctionType() &&
4388 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4389 TraitKind == UETT_PreferredAlignOf)) {
4390 // sizeof(function)/alignof(function) is allowed as an extension.
4391 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4392 << getTraitSpelling(TraitKind) << ArgRange;
4393 return false;
4396 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4397 // this is an error (OpenCL v1.1 s6.3.k)
4398 if (T->isVoidType()) {
4399 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4400 : diag::ext_sizeof_alignof_void_type;
4401 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4402 return false;
4405 return true;
4408 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4409 SourceLocation Loc,
4410 SourceRange ArgRange,
4411 UnaryExprOrTypeTrait TraitKind) {
4412 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4413 // runtime doesn't allow it.
4414 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4415 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4416 << T << (TraitKind == UETT_SizeOf)
4417 << ArgRange;
4418 return true;
4421 return false;
4424 /// Check whether E is a pointer from a decayed array type (the decayed
4425 /// pointer type is equal to T) and emit a warning if it is.
4426 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4427 const Expr *E) {
4428 // Don't warn if the operation changed the type.
4429 if (T != E->getType())
4430 return;
4432 // Now look for array decays.
4433 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4434 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4435 return;
4437 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4438 << ICE->getType()
4439 << ICE->getSubExpr()->getType();
4442 /// Check the constraints on expression operands to unary type expression
4443 /// and type traits.
4445 /// Completes any types necessary and validates the constraints on the operand
4446 /// expression. The logic mostly mirrors the type-based overload, but may modify
4447 /// the expression as it completes the type for that expression through template
4448 /// instantiation, etc.
4449 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4450 UnaryExprOrTypeTrait ExprKind) {
4451 QualType ExprTy = E->getType();
4452 assert(!ExprTy->isReferenceType());
4454 bool IsUnevaluatedOperand =
4455 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4456 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4457 ExprKind == UETT_VecStep);
4458 if (IsUnevaluatedOperand) {
4459 ExprResult Result = CheckUnevaluatedOperand(E);
4460 if (Result.isInvalid())
4461 return true;
4462 E = Result.get();
4465 // The operand for sizeof and alignof is in an unevaluated expression context,
4466 // so side effects could result in unintended consequences.
4467 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4468 // used to build SFINAE gadgets.
4469 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4470 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4471 !E->isInstantiationDependent() &&
4472 !E->getType()->isVariableArrayType() &&
4473 E->HasSideEffects(Context, false))
4474 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4476 if (ExprKind == UETT_VecStep)
4477 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4478 E->getSourceRange());
4480 if (ExprKind == UETT_VectorElements)
4481 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4482 E->getSourceRange());
4484 // Explicitly list some types as extensions.
4485 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4486 E->getSourceRange(), ExprKind))
4487 return false;
4489 // WebAssembly tables are always illegal operands to unary expressions and
4490 // type traits.
4491 if (Context.getTargetInfo().getTriple().isWasm() &&
4492 E->getType()->isWebAssemblyTableType()) {
4493 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4494 << getTraitSpelling(ExprKind);
4495 return true;
4498 // 'alignof' applied to an expression only requires the base element type of
4499 // the expression to be complete. 'sizeof' requires the expression's type to
4500 // be complete (and will attempt to complete it if it's an array of unknown
4501 // bound).
4502 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4503 if (RequireCompleteSizedType(
4504 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4505 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4506 getTraitSpelling(ExprKind), E->getSourceRange()))
4507 return true;
4508 } else {
4509 if (RequireCompleteSizedExprType(
4510 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4511 getTraitSpelling(ExprKind), E->getSourceRange()))
4512 return true;
4515 // Completing the expression's type may have changed it.
4516 ExprTy = E->getType();
4517 assert(!ExprTy->isReferenceType());
4519 if (ExprTy->isFunctionType()) {
4520 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4521 << getTraitSpelling(ExprKind) << E->getSourceRange();
4522 return true;
4525 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4526 E->getSourceRange(), ExprKind))
4527 return true;
4529 if (ExprKind == UETT_SizeOf) {
4530 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4531 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4532 QualType OType = PVD->getOriginalType();
4533 QualType Type = PVD->getType();
4534 if (Type->isPointerType() && OType->isArrayType()) {
4535 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4536 << Type << OType;
4537 Diag(PVD->getLocation(), diag::note_declared_at);
4542 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4543 // decays into a pointer and returns an unintended result. This is most
4544 // likely a typo for "sizeof(array) op x".
4545 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4546 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4547 BO->getLHS());
4548 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4549 BO->getRHS());
4553 return false;
4556 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4557 // Cannot know anything else if the expression is dependent.
4558 if (E->isTypeDependent())
4559 return false;
4561 if (E->getObjectKind() == OK_BitField) {
4562 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4563 << 1 << E->getSourceRange();
4564 return true;
4567 ValueDecl *D = nullptr;
4568 Expr *Inner = E->IgnoreParens();
4569 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4570 D = DRE->getDecl();
4571 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4572 D = ME->getMemberDecl();
4575 // If it's a field, require the containing struct to have a
4576 // complete definition so that we can compute the layout.
4578 // This can happen in C++11 onwards, either by naming the member
4579 // in a way that is not transformed into a member access expression
4580 // (in an unevaluated operand, for instance), or by naming the member
4581 // in a trailing-return-type.
4583 // For the record, since __alignof__ on expressions is a GCC
4584 // extension, GCC seems to permit this but always gives the
4585 // nonsensical answer 0.
4587 // We don't really need the layout here --- we could instead just
4588 // directly check for all the appropriate alignment-lowing
4589 // attributes --- but that would require duplicating a lot of
4590 // logic that just isn't worth duplicating for such a marginal
4591 // use-case.
4592 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4593 // Fast path this check, since we at least know the record has a
4594 // definition if we can find a member of it.
4595 if (!FD->getParent()->isCompleteDefinition()) {
4596 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4597 << E->getSourceRange();
4598 return true;
4601 // Otherwise, if it's a field, and the field doesn't have
4602 // reference type, then it must have a complete type (or be a
4603 // flexible array member, which we explicitly want to
4604 // white-list anyway), which makes the following checks trivial.
4605 if (!FD->getType()->isReferenceType())
4606 return false;
4609 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4612 bool Sema::CheckVecStepExpr(Expr *E) {
4613 E = E->IgnoreParens();
4615 // Cannot know anything else if the expression is dependent.
4616 if (E->isTypeDependent())
4617 return false;
4619 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4622 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4623 CapturingScopeInfo *CSI) {
4624 assert(T->isVariablyModifiedType());
4625 assert(CSI != nullptr);
4627 // We're going to walk down into the type and look for VLA expressions.
4628 do {
4629 const Type *Ty = T.getTypePtr();
4630 switch (Ty->getTypeClass()) {
4631 #define TYPE(Class, Base)
4632 #define ABSTRACT_TYPE(Class, Base)
4633 #define NON_CANONICAL_TYPE(Class, Base)
4634 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4635 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4636 #include "clang/AST/TypeNodes.inc"
4637 T = QualType();
4638 break;
4639 // These types are never variably-modified.
4640 case Type::Builtin:
4641 case Type::Complex:
4642 case Type::Vector:
4643 case Type::ExtVector:
4644 case Type::ConstantMatrix:
4645 case Type::Record:
4646 case Type::Enum:
4647 case Type::TemplateSpecialization:
4648 case Type::ObjCObject:
4649 case Type::ObjCInterface:
4650 case Type::ObjCObjectPointer:
4651 case Type::ObjCTypeParam:
4652 case Type::Pipe:
4653 case Type::BitInt:
4654 llvm_unreachable("type class is never variably-modified!");
4655 case Type::Elaborated:
4656 T = cast<ElaboratedType>(Ty)->getNamedType();
4657 break;
4658 case Type::Adjusted:
4659 T = cast<AdjustedType>(Ty)->getOriginalType();
4660 break;
4661 case Type::Decayed:
4662 T = cast<DecayedType>(Ty)->getPointeeType();
4663 break;
4664 case Type::Pointer:
4665 T = cast<PointerType>(Ty)->getPointeeType();
4666 break;
4667 case Type::BlockPointer:
4668 T = cast<BlockPointerType>(Ty)->getPointeeType();
4669 break;
4670 case Type::LValueReference:
4671 case Type::RValueReference:
4672 T = cast<ReferenceType>(Ty)->getPointeeType();
4673 break;
4674 case Type::MemberPointer:
4675 T = cast<MemberPointerType>(Ty)->getPointeeType();
4676 break;
4677 case Type::ConstantArray:
4678 case Type::IncompleteArray:
4679 // Losing element qualification here is fine.
4680 T = cast<ArrayType>(Ty)->getElementType();
4681 break;
4682 case Type::VariableArray: {
4683 // Losing element qualification here is fine.
4684 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4686 // Unknown size indication requires no size computation.
4687 // Otherwise, evaluate and record it.
4688 auto Size = VAT->getSizeExpr();
4689 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4690 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4691 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4693 T = VAT->getElementType();
4694 break;
4696 case Type::FunctionProto:
4697 case Type::FunctionNoProto:
4698 T = cast<FunctionType>(Ty)->getReturnType();
4699 break;
4700 case Type::Paren:
4701 case Type::TypeOf:
4702 case Type::UnaryTransform:
4703 case Type::Attributed:
4704 case Type::BTFTagAttributed:
4705 case Type::SubstTemplateTypeParm:
4706 case Type::MacroQualified:
4707 // Keep walking after single level desugaring.
4708 T = T.getSingleStepDesugaredType(Context);
4709 break;
4710 case Type::Typedef:
4711 T = cast<TypedefType>(Ty)->desugar();
4712 break;
4713 case Type::Decltype:
4714 T = cast<DecltypeType>(Ty)->desugar();
4715 break;
4716 case Type::Using:
4717 T = cast<UsingType>(Ty)->desugar();
4718 break;
4719 case Type::Auto:
4720 case Type::DeducedTemplateSpecialization:
4721 T = cast<DeducedType>(Ty)->getDeducedType();
4722 break;
4723 case Type::TypeOfExpr:
4724 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4725 break;
4726 case Type::Atomic:
4727 T = cast<AtomicType>(Ty)->getValueType();
4728 break;
4730 } while (!T.isNull() && T->isVariablyModifiedType());
4733 /// Check the constraints on operands to unary expression and type
4734 /// traits.
4736 /// This will complete any types necessary, and validate the various constraints
4737 /// on those operands.
4739 /// The UsualUnaryConversions() function is *not* called by this routine.
4740 /// C99 6.3.2.1p[2-4] all state:
4741 /// Except when it is the operand of the sizeof operator ...
4743 /// C++ [expr.sizeof]p4
4744 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4745 /// standard conversions are not applied to the operand of sizeof.
4747 /// This policy is followed for all of the unary trait expressions.
4748 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4749 SourceLocation OpLoc,
4750 SourceRange ExprRange,
4751 UnaryExprOrTypeTrait ExprKind,
4752 StringRef KWName) {
4753 if (ExprType->isDependentType())
4754 return false;
4756 // C++ [expr.sizeof]p2:
4757 // When applied to a reference or a reference type, the result
4758 // is the size of the referenced type.
4759 // C++11 [expr.alignof]p3:
4760 // When alignof is applied to a reference type, the result
4761 // shall be the alignment of the referenced type.
4762 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4763 ExprType = Ref->getPointeeType();
4765 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4766 // When alignof or _Alignof is applied to an array type, the result
4767 // is the alignment of the element type.
4768 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4769 ExprKind == UETT_OpenMPRequiredSimdAlign)
4770 ExprType = Context.getBaseElementType(ExprType);
4772 if (ExprKind == UETT_VecStep)
4773 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4775 if (ExprKind == UETT_VectorElements)
4776 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4777 ExprRange);
4779 // Explicitly list some types as extensions.
4780 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4781 ExprKind))
4782 return false;
4784 if (RequireCompleteSizedType(
4785 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4786 KWName, ExprRange))
4787 return true;
4789 if (ExprType->isFunctionType()) {
4790 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4791 return true;
4794 // WebAssembly tables are always illegal operands to unary expressions and
4795 // type traits.
4796 if (Context.getTargetInfo().getTriple().isWasm() &&
4797 ExprType->isWebAssemblyTableType()) {
4798 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4799 << getTraitSpelling(ExprKind);
4800 return true;
4803 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4804 ExprKind))
4805 return true;
4807 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4808 if (auto *TT = ExprType->getAs<TypedefType>()) {
4809 for (auto I = FunctionScopes.rbegin(),
4810 E = std::prev(FunctionScopes.rend());
4811 I != E; ++I) {
4812 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4813 if (CSI == nullptr)
4814 break;
4815 DeclContext *DC = nullptr;
4816 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4817 DC = LSI->CallOperator;
4818 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4819 DC = CRSI->TheCapturedDecl;
4820 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4821 DC = BSI->TheDecl;
4822 if (DC) {
4823 if (DC->containsDecl(TT->getDecl()))
4824 break;
4825 captureVariablyModifiedType(Context, ExprType, CSI);
4831 return false;
4834 /// Build a sizeof or alignof expression given a type operand.
4835 ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4836 SourceLocation OpLoc,
4837 UnaryExprOrTypeTrait ExprKind,
4838 SourceRange R) {
4839 if (!TInfo)
4840 return ExprError();
4842 QualType T = TInfo->getType();
4844 if (!T->isDependentType() &&
4845 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4846 getTraitSpelling(ExprKind)))
4847 return ExprError();
4849 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4850 // properly deal with VLAs in nested calls of sizeof and typeof.
4851 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4852 TInfo->getType()->isVariablyModifiedType())
4853 TInfo = TransformToPotentiallyEvaluated(TInfo);
4855 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4856 return new (Context) UnaryExprOrTypeTraitExpr(
4857 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4860 /// Build a sizeof or alignof expression given an expression
4861 /// operand.
4862 ExprResult
4863 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4864 UnaryExprOrTypeTrait ExprKind) {
4865 ExprResult PE = CheckPlaceholderExpr(E);
4866 if (PE.isInvalid())
4867 return ExprError();
4869 E = PE.get();
4871 // Verify that the operand is valid.
4872 bool isInvalid = false;
4873 if (E->isTypeDependent()) {
4874 // Delay type-checking for type-dependent expressions.
4875 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4876 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4877 } else if (ExprKind == UETT_VecStep) {
4878 isInvalid = CheckVecStepExpr(E);
4879 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4880 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4881 isInvalid = true;
4882 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4883 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4884 isInvalid = true;
4885 } else if (ExprKind == UETT_VectorElements) {
4886 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_VectorElements);
4887 } else {
4888 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4891 if (isInvalid)
4892 return ExprError();
4894 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4895 PE = TransformToPotentiallyEvaluated(E);
4896 if (PE.isInvalid()) return ExprError();
4897 E = PE.get();
4900 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4901 return new (Context) UnaryExprOrTypeTraitExpr(
4902 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4905 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4906 /// expr and the same for @c alignof and @c __alignof
4907 /// Note that the ArgRange is invalid if isType is false.
4908 ExprResult
4909 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4910 UnaryExprOrTypeTrait ExprKind, bool IsType,
4911 void *TyOrEx, SourceRange ArgRange) {
4912 // If error parsing type, ignore.
4913 if (!TyOrEx) return ExprError();
4915 if (IsType) {
4916 TypeSourceInfo *TInfo;
4917 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4918 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4921 Expr *ArgEx = (Expr *)TyOrEx;
4922 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4923 return Result;
4926 bool Sema::CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
4927 SourceLocation OpLoc, SourceRange R) {
4928 if (!TInfo)
4929 return true;
4930 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4931 UETT_AlignOf, KWName);
4934 /// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
4935 /// _Alignas(type-name) .
4936 /// [dcl.align] An alignment-specifier of the form
4937 /// alignas(type-id) has the same effect as alignas(alignof(type-id)).
4939 /// [N1570 6.7.5] _Alignas(type-name) is equivalent to
4940 /// _Alignas(_Alignof(type-name)).
4941 bool Sema::ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
4942 SourceLocation OpLoc, SourceRange R) {
4943 TypeSourceInfo *TInfo;
4944 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(Ty.getAsOpaquePtr()),
4945 &TInfo);
4946 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4949 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4950 bool IsReal) {
4951 if (V.get()->isTypeDependent())
4952 return S.Context.DependentTy;
4954 // _Real and _Imag are only l-values for normal l-values.
4955 if (V.get()->getObjectKind() != OK_Ordinary) {
4956 V = S.DefaultLvalueConversion(V.get());
4957 if (V.isInvalid())
4958 return QualType();
4961 // These operators return the element type of a complex type.
4962 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4963 return CT->getElementType();
4965 // Otherwise they pass through real integer and floating point types here.
4966 if (V.get()->getType()->isArithmeticType())
4967 return V.get()->getType();
4969 // Test for placeholders.
4970 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4971 if (PR.isInvalid()) return QualType();
4972 if (PR.get() != V.get()) {
4973 V = PR;
4974 return CheckRealImagOperand(S, V, Loc, IsReal);
4977 // Reject anything else.
4978 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4979 << (IsReal ? "__real" : "__imag");
4980 return QualType();
4985 ExprResult
4986 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4987 tok::TokenKind Kind, Expr *Input) {
4988 UnaryOperatorKind Opc;
4989 switch (Kind) {
4990 default: llvm_unreachable("Unknown unary op!");
4991 case tok::plusplus: Opc = UO_PostInc; break;
4992 case tok::minusminus: Opc = UO_PostDec; break;
4995 // Since this might is a postfix expression, get rid of ParenListExprs.
4996 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4997 if (Result.isInvalid()) return ExprError();
4998 Input = Result.get();
5000 return BuildUnaryOp(S, OpLoc, Opc, Input);
5003 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
5005 /// \return true on error
5006 static bool checkArithmeticOnObjCPointer(Sema &S,
5007 SourceLocation opLoc,
5008 Expr *op) {
5009 assert(op->getType()->isObjCObjectPointerType());
5010 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
5011 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
5012 return false;
5014 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
5015 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
5016 << op->getSourceRange();
5017 return true;
5020 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
5021 auto *BaseNoParens = Base->IgnoreParens();
5022 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
5023 return MSProp->getPropertyDecl()->getType()->isArrayType();
5024 return isa<MSPropertySubscriptExpr>(BaseNoParens);
5027 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
5028 // Typically this is DependentTy, but can sometimes be more precise.
5030 // There are cases when we could determine a non-dependent type:
5031 // - LHS and RHS may have non-dependent types despite being type-dependent
5032 // (e.g. unbounded array static members of the current instantiation)
5033 // - one may be a dependent-sized array with known element type
5034 // - one may be a dependent-typed valid index (enum in current instantiation)
5036 // We *always* return a dependent type, in such cases it is DependentTy.
5037 // This avoids creating type-dependent expressions with non-dependent types.
5038 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
5039 static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
5040 const ASTContext &Ctx) {
5041 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
5042 QualType LTy = LHS->getType(), RTy = RHS->getType();
5043 QualType Result = Ctx.DependentTy;
5044 if (RTy->isIntegralOrUnscopedEnumerationType()) {
5045 if (const PointerType *PT = LTy->getAs<PointerType>())
5046 Result = PT->getPointeeType();
5047 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
5048 Result = AT->getElementType();
5049 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
5050 if (const PointerType *PT = RTy->getAs<PointerType>())
5051 Result = PT->getPointeeType();
5052 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
5053 Result = AT->getElementType();
5055 // Ensure we return a dependent type.
5056 return Result->isDependentType() ? Result : Ctx.DependentTy;
5059 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args);
5061 ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
5062 SourceLocation lbLoc,
5063 MultiExprArg ArgExprs,
5064 SourceLocation rbLoc) {
5066 if (base && !base->getType().isNull() &&
5067 base->hasPlaceholderType(BuiltinType::OMPArraySection))
5068 return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(),
5069 SourceLocation(), /*Length*/ nullptr,
5070 /*Stride=*/nullptr, rbLoc);
5072 // Since this might be a postfix expression, get rid of ParenListExprs.
5073 if (isa<ParenListExpr>(base)) {
5074 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
5075 if (result.isInvalid())
5076 return ExprError();
5077 base = result.get();
5080 // Check if base and idx form a MatrixSubscriptExpr.
5082 // Helper to check for comma expressions, which are not allowed as indices for
5083 // matrix subscript expressions.
5084 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
5085 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
5086 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
5087 << SourceRange(base->getBeginLoc(), rbLoc);
5088 return true;
5090 return false;
5092 // The matrix subscript operator ([][])is considered a single operator.
5093 // Separating the index expressions by parenthesis is not allowed.
5094 if (base && !base->getType().isNull() &&
5095 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
5096 !isa<MatrixSubscriptExpr>(base)) {
5097 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
5098 << SourceRange(base->getBeginLoc(), rbLoc);
5099 return ExprError();
5101 // If the base is a MatrixSubscriptExpr, try to create a new
5102 // MatrixSubscriptExpr.
5103 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
5104 if (matSubscriptE) {
5105 assert(ArgExprs.size() == 1);
5106 if (CheckAndReportCommaError(ArgExprs.front()))
5107 return ExprError();
5109 assert(matSubscriptE->isIncomplete() &&
5110 "base has to be an incomplete matrix subscript");
5111 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
5112 matSubscriptE->getRowIdx(),
5113 ArgExprs.front(), rbLoc);
5115 if (base->getType()->isWebAssemblyTableType()) {
5116 Diag(base->getExprLoc(), diag::err_wasm_table_art)
5117 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5118 return ExprError();
5121 // Handle any non-overload placeholder types in the base and index
5122 // expressions. We can't handle overloads here because the other
5123 // operand might be an overloadable type, in which case the overload
5124 // resolution for the operator overload should get the first crack
5125 // at the overload.
5126 bool IsMSPropertySubscript = false;
5127 if (base->getType()->isNonOverloadPlaceholderType()) {
5128 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
5129 if (!IsMSPropertySubscript) {
5130 ExprResult result = CheckPlaceholderExpr(base);
5131 if (result.isInvalid())
5132 return ExprError();
5133 base = result.get();
5137 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5138 if (base->getType()->isMatrixType()) {
5139 assert(ArgExprs.size() == 1);
5140 if (CheckAndReportCommaError(ArgExprs.front()))
5141 return ExprError();
5143 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
5144 rbLoc);
5147 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5148 Expr *idx = ArgExprs[0];
5149 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
5150 (isa<CXXOperatorCallExpr>(idx) &&
5151 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
5152 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
5153 << SourceRange(base->getBeginLoc(), rbLoc);
5157 if (ArgExprs.size() == 1 &&
5158 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5159 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
5160 if (result.isInvalid())
5161 return ExprError();
5162 ArgExprs[0] = result.get();
5163 } else {
5164 if (checkArgsForPlaceholders(*this, ArgExprs))
5165 return ExprError();
5168 // Build an unanalyzed expression if either operand is type-dependent.
5169 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5170 (base->isTypeDependent() ||
5171 Expr::hasAnyTypeDependentArguments(ArgExprs)) &&
5172 !isa<PackExpansionExpr>(ArgExprs[0])) {
5173 return new (Context) ArraySubscriptExpr(
5174 base, ArgExprs.front(),
5175 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
5176 VK_LValue, OK_Ordinary, rbLoc);
5179 // MSDN, property (C++)
5180 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5181 // This attribute can also be used in the declaration of an empty array in a
5182 // class or structure definition. For example:
5183 // __declspec(property(get=GetX, put=PutX)) int x[];
5184 // The above statement indicates that x[] can be used with one or more array
5185 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5186 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5187 if (IsMSPropertySubscript) {
5188 assert(ArgExprs.size() == 1);
5189 // Build MS property subscript expression if base is MS property reference
5190 // or MS property subscript.
5191 return new (Context)
5192 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5193 VK_LValue, OK_Ordinary, rbLoc);
5196 // Use C++ overloaded-operator rules if either operand has record
5197 // type. The spec says to do this if either type is *overloadable*,
5198 // but enum types can't declare subscript operators or conversion
5199 // operators, so there's nothing interesting for overload resolution
5200 // to do if there aren't any record types involved.
5202 // ObjC pointers have their own subscripting logic that is not tied
5203 // to overload resolution and so should not take this path.
5204 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
5205 ((base->getType()->isRecordType() ||
5206 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
5207 ArgExprs[0]->getType()->isRecordType())))) {
5208 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
5211 ExprResult Res =
5212 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
5214 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
5215 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
5217 return Res;
5220 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
5221 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
5222 InitializationKind Kind =
5223 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
5224 InitializationSequence InitSeq(*this, Entity, Kind, E);
5225 return InitSeq.Perform(*this, Entity, Kind, E);
5228 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5229 Expr *ColumnIdx,
5230 SourceLocation RBLoc) {
5231 ExprResult BaseR = CheckPlaceholderExpr(Base);
5232 if (BaseR.isInvalid())
5233 return BaseR;
5234 Base = BaseR.get();
5236 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5237 if (RowR.isInvalid())
5238 return RowR;
5239 RowIdx = RowR.get();
5241 if (!ColumnIdx)
5242 return new (Context) MatrixSubscriptExpr(
5243 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5245 // Build an unanalyzed expression if any of the operands is type-dependent.
5246 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5247 ColumnIdx->isTypeDependent())
5248 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5249 Context.DependentTy, RBLoc);
5251 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5252 if (ColumnR.isInvalid())
5253 return ColumnR;
5254 ColumnIdx = ColumnR.get();
5256 // Check that IndexExpr is an integer expression. If it is a constant
5257 // expression, check that it is less than Dim (= the number of elements in the
5258 // corresponding dimension).
5259 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5260 bool IsColumnIdx) -> Expr * {
5261 if (!IndexExpr->getType()->isIntegerType() &&
5262 !IndexExpr->isTypeDependent()) {
5263 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5264 << IsColumnIdx;
5265 return nullptr;
5268 if (std::optional<llvm::APSInt> Idx =
5269 IndexExpr->getIntegerConstantExpr(Context)) {
5270 if ((*Idx < 0 || *Idx >= Dim)) {
5271 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5272 << IsColumnIdx << Dim;
5273 return nullptr;
5277 ExprResult ConvExpr =
5278 tryConvertExprToType(IndexExpr, Context.getSizeType());
5279 assert(!ConvExpr.isInvalid() &&
5280 "should be able to convert any integer type to size type");
5281 return ConvExpr.get();
5284 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5285 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5286 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5287 if (!RowIdx || !ColumnIdx)
5288 return ExprError();
5290 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5291 MTy->getElementType(), RBLoc);
5294 void Sema::CheckAddressOfNoDeref(const Expr *E) {
5295 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5296 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5298 // For expressions like `&(*s).b`, the base is recorded and what should be
5299 // checked.
5300 const MemberExpr *Member = nullptr;
5301 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5302 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5304 LastRecord.PossibleDerefs.erase(StrippedExpr);
5307 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5308 if (isUnevaluatedContext())
5309 return;
5311 QualType ResultTy = E->getType();
5312 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5314 // Bail if the element is an array since it is not memory access.
5315 if (isa<ArrayType>(ResultTy))
5316 return;
5318 if (ResultTy->hasAttr(attr::NoDeref)) {
5319 LastRecord.PossibleDerefs.insert(E);
5320 return;
5323 // Check if the base type is a pointer to a member access of a struct
5324 // marked with noderef.
5325 const Expr *Base = E->getBase();
5326 QualType BaseTy = Base->getType();
5327 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5328 // Not a pointer access
5329 return;
5331 const MemberExpr *Member = nullptr;
5332 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5333 Member->isArrow())
5334 Base = Member->getBase();
5336 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5337 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5338 LastRecord.PossibleDerefs.insert(E);
5342 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5343 Expr *LowerBound,
5344 SourceLocation ColonLocFirst,
5345 SourceLocation ColonLocSecond,
5346 Expr *Length, Expr *Stride,
5347 SourceLocation RBLoc) {
5348 if (Base->hasPlaceholderType() &&
5349 !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5350 ExprResult Result = CheckPlaceholderExpr(Base);
5351 if (Result.isInvalid())
5352 return ExprError();
5353 Base = Result.get();
5355 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
5356 ExprResult Result = CheckPlaceholderExpr(LowerBound);
5357 if (Result.isInvalid())
5358 return ExprError();
5359 Result = DefaultLvalueConversion(Result.get());
5360 if (Result.isInvalid())
5361 return ExprError();
5362 LowerBound = Result.get();
5364 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
5365 ExprResult Result = CheckPlaceholderExpr(Length);
5366 if (Result.isInvalid())
5367 return ExprError();
5368 Result = DefaultLvalueConversion(Result.get());
5369 if (Result.isInvalid())
5370 return ExprError();
5371 Length = Result.get();
5373 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
5374 ExprResult Result = CheckPlaceholderExpr(Stride);
5375 if (Result.isInvalid())
5376 return ExprError();
5377 Result = DefaultLvalueConversion(Result.get());
5378 if (Result.isInvalid())
5379 return ExprError();
5380 Stride = Result.get();
5383 // Build an unanalyzed expression if either operand is type-dependent.
5384 if (Base->isTypeDependent() ||
5385 (LowerBound &&
5386 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
5387 (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
5388 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
5389 return new (Context) OMPArraySectionExpr(
5390 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
5391 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5394 // Perform default conversions.
5395 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
5396 QualType ResultTy;
5397 if (OriginalTy->isAnyPointerType()) {
5398 ResultTy = OriginalTy->getPointeeType();
5399 } else if (OriginalTy->isArrayType()) {
5400 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
5401 } else {
5402 return ExprError(
5403 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
5404 << Base->getSourceRange());
5406 // C99 6.5.2.1p1
5407 if (LowerBound) {
5408 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
5409 LowerBound);
5410 if (Res.isInvalid())
5411 return ExprError(Diag(LowerBound->getExprLoc(),
5412 diag::err_omp_typecheck_section_not_integer)
5413 << 0 << LowerBound->getSourceRange());
5414 LowerBound = Res.get();
5416 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5417 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5418 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
5419 << 0 << LowerBound->getSourceRange();
5421 if (Length) {
5422 auto Res =
5423 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
5424 if (Res.isInvalid())
5425 return ExprError(Diag(Length->getExprLoc(),
5426 diag::err_omp_typecheck_section_not_integer)
5427 << 1 << Length->getSourceRange());
5428 Length = Res.get();
5430 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5431 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5432 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5433 << 1 << Length->getSourceRange();
5435 if (Stride) {
5436 ExprResult Res =
5437 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
5438 if (Res.isInvalid())
5439 return ExprError(Diag(Stride->getExprLoc(),
5440 diag::err_omp_typecheck_section_not_integer)
5441 << 1 << Stride->getSourceRange());
5442 Stride = Res.get();
5444 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5445 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5446 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5447 << 1 << Stride->getSourceRange();
5450 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5451 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5452 // type. Note that functions are not objects, and that (in C99 parlance)
5453 // incomplete types are not object types.
5454 if (ResultTy->isFunctionType()) {
5455 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5456 << ResultTy << Base->getSourceRange();
5457 return ExprError();
5460 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5461 diag::err_omp_section_incomplete_type, Base))
5462 return ExprError();
5464 if (LowerBound && !OriginalTy->isAnyPointerType()) {
5465 Expr::EvalResult Result;
5466 if (LowerBound->EvaluateAsInt(Result, Context)) {
5467 // OpenMP 5.0, [2.1.5 Array Sections]
5468 // The array section must be a subset of the original array.
5469 llvm::APSInt LowerBoundValue = Result.Val.getInt();
5470 if (LowerBoundValue.isNegative()) {
5471 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5472 << LowerBound->getSourceRange();
5473 return ExprError();
5478 if (Length) {
5479 Expr::EvalResult Result;
5480 if (Length->EvaluateAsInt(Result, Context)) {
5481 // OpenMP 5.0, [2.1.5 Array Sections]
5482 // The length must evaluate to non-negative integers.
5483 llvm::APSInt LengthValue = Result.Val.getInt();
5484 if (LengthValue.isNegative()) {
5485 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5486 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5487 << Length->getSourceRange();
5488 return ExprError();
5491 } else if (ColonLocFirst.isValid() &&
5492 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5493 !OriginalTy->isVariableArrayType()))) {
5494 // OpenMP 5.0, [2.1.5 Array Sections]
5495 // When the size of the array dimension is not known, the length must be
5496 // specified explicitly.
5497 Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5498 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5499 return ExprError();
5502 if (Stride) {
5503 Expr::EvalResult Result;
5504 if (Stride->EvaluateAsInt(Result, Context)) {
5505 // OpenMP 5.0, [2.1.5 Array Sections]
5506 // The stride must evaluate to a positive integer.
5507 llvm::APSInt StrideValue = Result.Val.getInt();
5508 if (!StrideValue.isStrictlyPositive()) {
5509 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5510 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5511 << Stride->getSourceRange();
5512 return ExprError();
5517 if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5518 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5519 if (Result.isInvalid())
5520 return ExprError();
5521 Base = Result.get();
5523 return new (Context) OMPArraySectionExpr(
5524 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5525 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5528 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5529 SourceLocation RParenLoc,
5530 ArrayRef<Expr *> Dims,
5531 ArrayRef<SourceRange> Brackets) {
5532 if (Base->hasPlaceholderType()) {
5533 ExprResult Result = CheckPlaceholderExpr(Base);
5534 if (Result.isInvalid())
5535 return ExprError();
5536 Result = DefaultLvalueConversion(Result.get());
5537 if (Result.isInvalid())
5538 return ExprError();
5539 Base = Result.get();
5541 QualType BaseTy = Base->getType();
5542 // Delay analysis of the types/expressions if instantiation/specialization is
5543 // required.
5544 if (!BaseTy->isPointerType() && Base->isTypeDependent())
5545 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5546 LParenLoc, RParenLoc, Dims, Brackets);
5547 if (!BaseTy->isPointerType() ||
5548 (!Base->isTypeDependent() &&
5549 BaseTy->getPointeeType()->isIncompleteType()))
5550 return ExprError(Diag(Base->getExprLoc(),
5551 diag::err_omp_non_pointer_type_array_shaping_base)
5552 << Base->getSourceRange());
5554 SmallVector<Expr *, 4> NewDims;
5555 bool ErrorFound = false;
5556 for (Expr *Dim : Dims) {
5557 if (Dim->hasPlaceholderType()) {
5558 ExprResult Result = CheckPlaceholderExpr(Dim);
5559 if (Result.isInvalid()) {
5560 ErrorFound = true;
5561 continue;
5563 Result = DefaultLvalueConversion(Result.get());
5564 if (Result.isInvalid()) {
5565 ErrorFound = true;
5566 continue;
5568 Dim = Result.get();
5570 if (!Dim->isTypeDependent()) {
5571 ExprResult Result =
5572 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5573 if (Result.isInvalid()) {
5574 ErrorFound = true;
5575 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5576 << Dim->getSourceRange();
5577 continue;
5579 Dim = Result.get();
5580 Expr::EvalResult EvResult;
5581 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5582 // OpenMP 5.0, [2.1.4 Array Shaping]
5583 // Each si is an integral type expression that must evaluate to a
5584 // positive integer.
5585 llvm::APSInt Value = EvResult.Val.getInt();
5586 if (!Value.isStrictlyPositive()) {
5587 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5588 << toString(Value, /*Radix=*/10, /*Signed=*/true)
5589 << Dim->getSourceRange();
5590 ErrorFound = true;
5591 continue;
5595 NewDims.push_back(Dim);
5597 if (ErrorFound)
5598 return ExprError();
5599 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5600 LParenLoc, RParenLoc, NewDims, Brackets);
5603 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5604 SourceLocation LLoc, SourceLocation RLoc,
5605 ArrayRef<OMPIteratorData> Data) {
5606 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5607 bool IsCorrect = true;
5608 for (const OMPIteratorData &D : Data) {
5609 TypeSourceInfo *TInfo = nullptr;
5610 SourceLocation StartLoc;
5611 QualType DeclTy;
5612 if (!D.Type.getAsOpaquePtr()) {
5613 // OpenMP 5.0, 2.1.6 Iterators
5614 // In an iterator-specifier, if the iterator-type is not specified then
5615 // the type of that iterator is of int type.
5616 DeclTy = Context.IntTy;
5617 StartLoc = D.DeclIdentLoc;
5618 } else {
5619 DeclTy = GetTypeFromParser(D.Type, &TInfo);
5620 StartLoc = TInfo->getTypeLoc().getBeginLoc();
5623 bool IsDeclTyDependent = DeclTy->isDependentType() ||
5624 DeclTy->containsUnexpandedParameterPack() ||
5625 DeclTy->isInstantiationDependentType();
5626 if (!IsDeclTyDependent) {
5627 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5628 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5629 // The iterator-type must be an integral or pointer type.
5630 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5631 << DeclTy;
5632 IsCorrect = false;
5633 continue;
5635 if (DeclTy.isConstant(Context)) {
5636 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5637 // The iterator-type must not be const qualified.
5638 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5639 << DeclTy;
5640 IsCorrect = false;
5641 continue;
5645 // Iterator declaration.
5646 assert(D.DeclIdent && "Identifier expected.");
5647 // Always try to create iterator declarator to avoid extra error messages
5648 // about unknown declarations use.
5649 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5650 D.DeclIdent, DeclTy, TInfo, SC_None);
5651 VD->setImplicit();
5652 if (S) {
5653 // Check for conflicting previous declaration.
5654 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5655 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5656 ForVisibleRedeclaration);
5657 Previous.suppressDiagnostics();
5658 LookupName(Previous, S);
5660 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5661 /*AllowInlineNamespace=*/false);
5662 if (!Previous.empty()) {
5663 NamedDecl *Old = Previous.getRepresentativeDecl();
5664 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5665 Diag(Old->getLocation(), diag::note_previous_definition);
5666 } else {
5667 PushOnScopeChains(VD, S);
5669 } else {
5670 CurContext->addDecl(VD);
5673 /// Act on the iterator variable declaration.
5674 ActOnOpenMPIteratorVarDecl(VD);
5676 Expr *Begin = D.Range.Begin;
5677 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5678 ExprResult BeginRes =
5679 PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5680 Begin = BeginRes.get();
5682 Expr *End = D.Range.End;
5683 if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5684 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5685 End = EndRes.get();
5687 Expr *Step = D.Range.Step;
5688 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5689 if (!Step->getType()->isIntegralType(Context)) {
5690 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5691 << Step << Step->getSourceRange();
5692 IsCorrect = false;
5693 continue;
5695 std::optional<llvm::APSInt> Result =
5696 Step->getIntegerConstantExpr(Context);
5697 // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5698 // If the step expression of a range-specification equals zero, the
5699 // behavior is unspecified.
5700 if (Result && Result->isZero()) {
5701 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5702 << Step << Step->getSourceRange();
5703 IsCorrect = false;
5704 continue;
5707 if (!Begin || !End || !IsCorrect) {
5708 IsCorrect = false;
5709 continue;
5711 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5712 IDElem.IteratorDecl = VD;
5713 IDElem.AssignmentLoc = D.AssignLoc;
5714 IDElem.Range.Begin = Begin;
5715 IDElem.Range.End = End;
5716 IDElem.Range.Step = Step;
5717 IDElem.ColonLoc = D.ColonLoc;
5718 IDElem.SecondColonLoc = D.SecColonLoc;
5720 if (!IsCorrect) {
5721 // Invalidate all created iterator declarations if error is found.
5722 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5723 if (Decl *ID = D.IteratorDecl)
5724 ID->setInvalidDecl();
5726 return ExprError();
5728 SmallVector<OMPIteratorHelperData, 4> Helpers;
5729 if (!CurContext->isDependentContext()) {
5730 // Build number of ityeration for each iteration range.
5731 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5732 // ((Begini-Stepi-1-Endi) / -Stepi);
5733 for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5734 // (Endi - Begini)
5735 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5736 D.Range.Begin);
5737 if(!Res.isUsable()) {
5738 IsCorrect = false;
5739 continue;
5741 ExprResult St, St1;
5742 if (D.Range.Step) {
5743 St = D.Range.Step;
5744 // (Endi - Begini) + Stepi
5745 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5746 if (!Res.isUsable()) {
5747 IsCorrect = false;
5748 continue;
5750 // (Endi - Begini) + Stepi - 1
5751 Res =
5752 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5753 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5754 if (!Res.isUsable()) {
5755 IsCorrect = false;
5756 continue;
5758 // ((Endi - Begini) + Stepi - 1) / Stepi
5759 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5760 if (!Res.isUsable()) {
5761 IsCorrect = false;
5762 continue;
5764 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5765 // (Begini - Endi)
5766 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5767 D.Range.Begin, D.Range.End);
5768 if (!Res1.isUsable()) {
5769 IsCorrect = false;
5770 continue;
5772 // (Begini - Endi) - Stepi
5773 Res1 =
5774 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5775 if (!Res1.isUsable()) {
5776 IsCorrect = false;
5777 continue;
5779 // (Begini - Endi) - Stepi - 1
5780 Res1 =
5781 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5782 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5783 if (!Res1.isUsable()) {
5784 IsCorrect = false;
5785 continue;
5787 // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5788 Res1 =
5789 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5790 if (!Res1.isUsable()) {
5791 IsCorrect = false;
5792 continue;
5794 // Stepi > 0.
5795 ExprResult CmpRes =
5796 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5797 ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5798 if (!CmpRes.isUsable()) {
5799 IsCorrect = false;
5800 continue;
5802 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5803 Res.get(), Res1.get());
5804 if (!Res.isUsable()) {
5805 IsCorrect = false;
5806 continue;
5809 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5810 if (!Res.isUsable()) {
5811 IsCorrect = false;
5812 continue;
5815 // Build counter update.
5816 // Build counter.
5817 auto *CounterVD =
5818 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5819 D.IteratorDecl->getBeginLoc(), nullptr,
5820 Res.get()->getType(), nullptr, SC_None);
5821 CounterVD->setImplicit();
5822 ExprResult RefRes =
5823 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5824 D.IteratorDecl->getBeginLoc());
5825 // Build counter update.
5826 // I = Begini + counter * Stepi;
5827 ExprResult UpdateRes;
5828 if (D.Range.Step) {
5829 UpdateRes = CreateBuiltinBinOp(
5830 D.AssignmentLoc, BO_Mul,
5831 DefaultLvalueConversion(RefRes.get()).get(), St.get());
5832 } else {
5833 UpdateRes = DefaultLvalueConversion(RefRes.get());
5835 if (!UpdateRes.isUsable()) {
5836 IsCorrect = false;
5837 continue;
5839 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5840 UpdateRes.get());
5841 if (!UpdateRes.isUsable()) {
5842 IsCorrect = false;
5843 continue;
5845 ExprResult VDRes =
5846 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5847 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5848 D.IteratorDecl->getBeginLoc());
5849 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5850 UpdateRes.get());
5851 if (!UpdateRes.isUsable()) {
5852 IsCorrect = false;
5853 continue;
5855 UpdateRes =
5856 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5857 if (!UpdateRes.isUsable()) {
5858 IsCorrect = false;
5859 continue;
5861 ExprResult CounterUpdateRes =
5862 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5863 if (!CounterUpdateRes.isUsable()) {
5864 IsCorrect = false;
5865 continue;
5867 CounterUpdateRes =
5868 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5869 if (!CounterUpdateRes.isUsable()) {
5870 IsCorrect = false;
5871 continue;
5873 OMPIteratorHelperData &HD = Helpers.emplace_back();
5874 HD.CounterVD = CounterVD;
5875 HD.Upper = Res.get();
5876 HD.Update = UpdateRes.get();
5877 HD.CounterUpdate = CounterUpdateRes.get();
5879 } else {
5880 Helpers.assign(ID.size(), {});
5882 if (!IsCorrect) {
5883 // Invalidate all created iterator declarations if error is found.
5884 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5885 if (Decl *ID = D.IteratorDecl)
5886 ID->setInvalidDecl();
5888 return ExprError();
5890 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5891 LLoc, RLoc, ID, Helpers);
5894 ExprResult
5895 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5896 Expr *Idx, SourceLocation RLoc) {
5897 Expr *LHSExp = Base;
5898 Expr *RHSExp = Idx;
5900 ExprValueKind VK = VK_LValue;
5901 ExprObjectKind OK = OK_Ordinary;
5903 // Per C++ core issue 1213, the result is an xvalue if either operand is
5904 // a non-lvalue array, and an lvalue otherwise.
5905 if (getLangOpts().CPlusPlus11) {
5906 for (auto *Op : {LHSExp, RHSExp}) {
5907 Op = Op->IgnoreImplicit();
5908 if (Op->getType()->isArrayType() && !Op->isLValue())
5909 VK = VK_XValue;
5913 // Perform default conversions.
5914 if (!LHSExp->getType()->getAs<VectorType>()) {
5915 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5916 if (Result.isInvalid())
5917 return ExprError();
5918 LHSExp = Result.get();
5920 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5921 if (Result.isInvalid())
5922 return ExprError();
5923 RHSExp = Result.get();
5925 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5927 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5928 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5929 // in the subscript position. As a result, we need to derive the array base
5930 // and index from the expression types.
5931 Expr *BaseExpr, *IndexExpr;
5932 QualType ResultType;
5933 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5934 BaseExpr = LHSExp;
5935 IndexExpr = RHSExp;
5936 ResultType =
5937 getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());
5938 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5939 BaseExpr = LHSExp;
5940 IndexExpr = RHSExp;
5941 ResultType = PTy->getPointeeType();
5942 } else if (const ObjCObjectPointerType *PTy =
5943 LHSTy->getAs<ObjCObjectPointerType>()) {
5944 BaseExpr = LHSExp;
5945 IndexExpr = RHSExp;
5947 // Use custom logic if this should be the pseudo-object subscript
5948 // expression.
5949 if (!LangOpts.isSubscriptPointerArithmetic())
5950 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5951 nullptr);
5953 ResultType = PTy->getPointeeType();
5954 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5955 // Handle the uncommon case of "123[Ptr]".
5956 BaseExpr = RHSExp;
5957 IndexExpr = LHSExp;
5958 ResultType = PTy->getPointeeType();
5959 } else if (const ObjCObjectPointerType *PTy =
5960 RHSTy->getAs<ObjCObjectPointerType>()) {
5961 // Handle the uncommon case of "123[Ptr]".
5962 BaseExpr = RHSExp;
5963 IndexExpr = LHSExp;
5964 ResultType = PTy->getPointeeType();
5965 if (!LangOpts.isSubscriptPointerArithmetic()) {
5966 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5967 << ResultType << BaseExpr->getSourceRange();
5968 return ExprError();
5970 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5971 BaseExpr = LHSExp; // vectors: V[123]
5972 IndexExpr = RHSExp;
5973 // We apply C++ DR1213 to vector subscripting too.
5974 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5975 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5976 if (Materialized.isInvalid())
5977 return ExprError();
5978 LHSExp = Materialized.get();
5980 VK = LHSExp->getValueKind();
5981 if (VK != VK_PRValue)
5982 OK = OK_VectorComponent;
5984 ResultType = VTy->getElementType();
5985 QualType BaseType = BaseExpr->getType();
5986 Qualifiers BaseQuals = BaseType.getQualifiers();
5987 Qualifiers MemberQuals = ResultType.getQualifiers();
5988 Qualifiers Combined = BaseQuals + MemberQuals;
5989 if (Combined != MemberQuals)
5990 ResultType = Context.getQualifiedType(ResultType, Combined);
5991 } else if (LHSTy->isBuiltinType() &&
5992 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5993 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5994 if (BTy->isSVEBool())
5995 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5996 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5998 BaseExpr = LHSExp;
5999 IndexExpr = RHSExp;
6000 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
6001 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
6002 if (Materialized.isInvalid())
6003 return ExprError();
6004 LHSExp = Materialized.get();
6006 VK = LHSExp->getValueKind();
6007 if (VK != VK_PRValue)
6008 OK = OK_VectorComponent;
6010 ResultType = BTy->getSveEltType(Context);
6012 QualType BaseType = BaseExpr->getType();
6013 Qualifiers BaseQuals = BaseType.getQualifiers();
6014 Qualifiers MemberQuals = ResultType.getQualifiers();
6015 Qualifiers Combined = BaseQuals + MemberQuals;
6016 if (Combined != MemberQuals)
6017 ResultType = Context.getQualifiedType(ResultType, Combined);
6018 } else if (LHSTy->isArrayType()) {
6019 // If we see an array that wasn't promoted by
6020 // DefaultFunctionArrayLvalueConversion, it must be an array that
6021 // wasn't promoted because of the C90 rule that doesn't
6022 // allow promoting non-lvalue arrays. Warn, then
6023 // force the promotion here.
6024 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
6025 << LHSExp->getSourceRange();
6026 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
6027 CK_ArrayToPointerDecay).get();
6028 LHSTy = LHSExp->getType();
6030 BaseExpr = LHSExp;
6031 IndexExpr = RHSExp;
6032 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
6033 } else if (RHSTy->isArrayType()) {
6034 // Same as previous, except for 123[f().a] case
6035 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
6036 << RHSExp->getSourceRange();
6037 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
6038 CK_ArrayToPointerDecay).get();
6039 RHSTy = RHSExp->getType();
6041 BaseExpr = RHSExp;
6042 IndexExpr = LHSExp;
6043 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
6044 } else {
6045 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
6046 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
6048 // C99 6.5.2.1p1
6049 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
6050 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
6051 << IndexExpr->getSourceRange());
6053 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
6054 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
6055 !IndexExpr->isTypeDependent()) {
6056 std::optional<llvm::APSInt> IntegerContantExpr =
6057 IndexExpr->getIntegerConstantExpr(getASTContext());
6058 if (!IntegerContantExpr.has_value() ||
6059 IntegerContantExpr.value().isNegative())
6060 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
6063 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
6064 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
6065 // type. Note that Functions are not objects, and that (in C99 parlance)
6066 // incomplete types are not object types.
6067 if (ResultType->isFunctionType()) {
6068 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
6069 << ResultType << BaseExpr->getSourceRange();
6070 return ExprError();
6073 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
6074 // GNU extension: subscripting on pointer to void
6075 Diag(LLoc, diag::ext_gnu_subscript_void_type)
6076 << BaseExpr->getSourceRange();
6078 // C forbids expressions of unqualified void type from being l-values.
6079 // See IsCForbiddenLValueType.
6080 if (!ResultType.hasQualifiers())
6081 VK = VK_PRValue;
6082 } else if (!ResultType->isDependentType() &&
6083 !ResultType.isWebAssemblyReferenceType() &&
6084 RequireCompleteSizedType(
6085 LLoc, ResultType,
6086 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
6087 return ExprError();
6089 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
6090 !ResultType.isCForbiddenLValueType());
6092 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
6093 FunctionScopes.size() > 1) {
6094 if (auto *TT =
6095 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
6096 for (auto I = FunctionScopes.rbegin(),
6097 E = std::prev(FunctionScopes.rend());
6098 I != E; ++I) {
6099 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
6100 if (CSI == nullptr)
6101 break;
6102 DeclContext *DC = nullptr;
6103 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
6104 DC = LSI->CallOperator;
6105 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
6106 DC = CRSI->TheCapturedDecl;
6107 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
6108 DC = BSI->TheDecl;
6109 if (DC) {
6110 if (DC->containsDecl(TT->getDecl()))
6111 break;
6112 captureVariablyModifiedType(
6113 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
6119 return new (Context)
6120 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
6123 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
6124 ParmVarDecl *Param, Expr *RewrittenInit,
6125 bool SkipImmediateInvocations) {
6126 if (Param->hasUnparsedDefaultArg()) {
6127 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
6128 // If we've already cleared out the location for the default argument,
6129 // that means we're parsing it right now.
6130 if (!UnparsedDefaultArgLocs.count(Param)) {
6131 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
6132 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
6133 Param->setInvalidDecl();
6134 return true;
6137 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
6138 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
6139 Diag(UnparsedDefaultArgLocs[Param],
6140 diag::note_default_argument_declared_here);
6141 return true;
6144 if (Param->hasUninstantiatedDefaultArg()) {
6145 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
6146 if (InstantiateDefaultArgument(CallLoc, FD, Param))
6147 return true;
6150 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
6151 assert(Init && "default argument but no initializer?");
6153 // If the default expression creates temporaries, we need to
6154 // push them to the current stack of expression temporaries so they'll
6155 // be properly destroyed.
6156 // FIXME: We should really be rebuilding the default argument with new
6157 // bound temporaries; see the comment in PR5810.
6158 // We don't need to do that with block decls, though, because
6159 // blocks in default argument expression can never capture anything.
6160 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
6161 // Set the "needs cleanups" bit regardless of whether there are
6162 // any explicit objects.
6163 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
6164 // Append all the objects to the cleanup list. Right now, this
6165 // should always be a no-op, because blocks in default argument
6166 // expressions should never be able to capture anything.
6167 assert(!InitWithCleanup->getNumObjects() &&
6168 "default argument expression has capturing blocks?");
6170 // C++ [expr.const]p15.1:
6171 // An expression or conversion is in an immediate function context if it is
6172 // potentially evaluated and [...] its innermost enclosing non-block scope
6173 // is a function parameter scope of an immediate function.
6174 EnterExpressionEvaluationContext EvalContext(
6175 *this,
6176 FD->isImmediateFunction()
6177 ? ExpressionEvaluationContext::ImmediateFunctionContext
6178 : ExpressionEvaluationContext::PotentiallyEvaluated,
6179 Param);
6180 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
6181 SkipImmediateInvocations;
6182 runWithSufficientStackSpace(CallLoc, [&] {
6183 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
6185 return false;
6188 struct ImmediateCallVisitor : public RecursiveASTVisitor<ImmediateCallVisitor> {
6189 const ASTContext &Context;
6190 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {}
6192 bool HasImmediateCalls = false;
6193 bool shouldVisitImplicitCode() const { return true; }
6195 bool VisitCallExpr(CallExpr *E) {
6196 if (const FunctionDecl *FD = E->getDirectCallee())
6197 HasImmediateCalls |= FD->isImmediateFunction();
6198 return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);
6201 // SourceLocExpr are not immediate invocations
6202 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
6203 // need to be rebuilt so that they refer to the correct SourceLocation and
6204 // DeclContext.
6205 bool VisitSourceLocExpr(SourceLocExpr *E) {
6206 HasImmediateCalls = true;
6207 return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);
6210 // A nested lambda might have parameters with immediate invocations
6211 // in their default arguments.
6212 // The compound statement is not visited (as it does not constitute a
6213 // subexpression).
6214 // FIXME: We should consider visiting and transforming captures
6215 // with init expressions.
6216 bool VisitLambdaExpr(LambdaExpr *E) {
6217 return VisitCXXMethodDecl(E->getCallOperator());
6220 // Blocks don't support default parameters, and, as for lambdas,
6221 // we don't consider their body a subexpression.
6222 bool VisitBlockDecl(BlockDecl *B) { return false; }
6224 bool VisitCompoundStmt(CompoundStmt *B) { return false; }
6226 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
6227 return TraverseStmt(E->getExpr());
6230 bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
6231 return TraverseStmt(E->getExpr());
6235 struct EnsureImmediateInvocationInDefaultArgs
6236 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
6237 EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
6238 : TreeTransform(SemaRef) {}
6240 // Lambda can only have immediate invocations in the default
6241 // args of their parameters, which is transformed upon calling the closure.
6242 // The body is not a subexpression, so we have nothing to do.
6243 // FIXME: Immediate calls in capture initializers should be transformed.
6244 ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; }
6245 ExprResult TransformBlockExpr(BlockExpr *E) { return E; }
6247 // Make sure we don't rebuild the this pointer as it would
6248 // cause it to incorrectly point it to the outermost class
6249 // in the case of nested struct initialization.
6250 ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }
6253 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
6254 FunctionDecl *FD, ParmVarDecl *Param,
6255 Expr *Init) {
6256 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
6258 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6260 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
6261 InitializationContext =
6262 OutermostDeclarationWithDelayedImmediateInvocations();
6263 if (!InitializationContext.has_value())
6264 InitializationContext.emplace(CallLoc, Param, CurContext);
6266 if (!Init && !Param->hasUnparsedDefaultArg()) {
6267 // Mark that we are replacing a default argument first.
6268 // If we are instantiating a template we won't have to
6269 // retransform immediate calls.
6270 // C++ [expr.const]p15.1:
6271 // An expression or conversion is in an immediate function context if it
6272 // is potentially evaluated and [...] its innermost enclosing non-block
6273 // scope is a function parameter scope of an immediate function.
6274 EnterExpressionEvaluationContext EvalContext(
6275 *this,
6276 FD->isImmediateFunction()
6277 ? ExpressionEvaluationContext::ImmediateFunctionContext
6278 : ExpressionEvaluationContext::PotentiallyEvaluated,
6279 Param);
6281 if (Param->hasUninstantiatedDefaultArg()) {
6282 if (InstantiateDefaultArgument(CallLoc, FD, Param))
6283 return ExprError();
6285 // CWG2631
6286 // An immediate invocation that is not evaluated where it appears is
6287 // evaluated and checked for whether it is a constant expression at the
6288 // point where the enclosing initializer is used in a function call.
6289 ImmediateCallVisitor V(getASTContext());
6290 if (!NestedDefaultChecking)
6291 V.TraverseDecl(Param);
6292 if (V.HasImmediateCalls) {
6293 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
6294 CallLoc, Param, CurContext};
6295 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
6296 ExprResult Res;
6297 runWithSufficientStackSpace(CallLoc, [&] {
6298 Res = Immediate.TransformInitializer(Param->getInit(),
6299 /*NotCopy=*/false);
6301 if (Res.isInvalid())
6302 return ExprError();
6303 Res = ConvertParamDefaultArgument(Param, Res.get(),
6304 Res.get()->getBeginLoc());
6305 if (Res.isInvalid())
6306 return ExprError();
6307 Init = Res.get();
6311 if (CheckCXXDefaultArgExpr(
6312 CallLoc, FD, Param, Init,
6313 /*SkipImmediateInvocations=*/NestedDefaultChecking))
6314 return ExprError();
6316 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
6317 Init, InitializationContext->Context);
6320 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
6321 assert(Field->hasInClassInitializer());
6323 // If we might have already tried and failed to instantiate, don't try again.
6324 if (Field->isInvalidDecl())
6325 return ExprError();
6327 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
6329 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
6331 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
6332 InitializationContext =
6333 OutermostDeclarationWithDelayedImmediateInvocations();
6334 if (!InitializationContext.has_value())
6335 InitializationContext.emplace(Loc, Field, CurContext);
6337 Expr *Init = nullptr;
6339 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
6341 EnterExpressionEvaluationContext EvalContext(
6342 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
6344 if (!Field->getInClassInitializer()) {
6345 // Maybe we haven't instantiated the in-class initializer. Go check the
6346 // pattern FieldDecl to see if it has one.
6347 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
6348 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
6349 DeclContext::lookup_result Lookup =
6350 ClassPattern->lookup(Field->getDeclName());
6352 FieldDecl *Pattern = nullptr;
6353 for (auto *L : Lookup) {
6354 if ((Pattern = dyn_cast<FieldDecl>(L)))
6355 break;
6357 assert(Pattern && "We must have set the Pattern!");
6358 if (!Pattern->hasInClassInitializer() ||
6359 InstantiateInClassInitializer(Loc, Field, Pattern,
6360 getTemplateInstantiationArgs(Field))) {
6361 Field->setInvalidDecl();
6362 return ExprError();
6367 // CWG2631
6368 // An immediate invocation that is not evaluated where it appears is
6369 // evaluated and checked for whether it is a constant expression at the
6370 // point where the enclosing initializer is used in a [...] a constructor
6371 // definition, or an aggregate initialization.
6372 ImmediateCallVisitor V(getASTContext());
6373 if (!NestedDefaultChecking)
6374 V.TraverseDecl(Field);
6375 if (V.HasImmediateCalls) {
6376 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
6377 CurContext};
6378 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
6379 NestedDefaultChecking;
6381 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
6382 ExprResult Res;
6383 runWithSufficientStackSpace(Loc, [&] {
6384 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
6385 /*CXXDirectInit=*/false);
6387 if (!Res.isInvalid())
6388 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
6389 if (Res.isInvalid()) {
6390 Field->setInvalidDecl();
6391 return ExprError();
6393 Init = Res.get();
6396 if (Field->getInClassInitializer()) {
6397 Expr *E = Init ? Init : Field->getInClassInitializer();
6398 if (!NestedDefaultChecking)
6399 runWithSufficientStackSpace(Loc, [&] {
6400 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
6402 // C++11 [class.base.init]p7:
6403 // The initialization of each base and member constitutes a
6404 // full-expression.
6405 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
6406 if (Res.isInvalid()) {
6407 Field->setInvalidDecl();
6408 return ExprError();
6410 Init = Res.get();
6412 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
6413 Field, InitializationContext->Context,
6414 Init);
6417 // DR1351:
6418 // If the brace-or-equal-initializer of a non-static data member
6419 // invokes a defaulted default constructor of its class or of an
6420 // enclosing class in a potentially evaluated subexpression, the
6421 // program is ill-formed.
6423 // This resolution is unworkable: the exception specification of the
6424 // default constructor can be needed in an unevaluated context, in
6425 // particular, in the operand of a noexcept-expression, and we can be
6426 // unable to compute an exception specification for an enclosed class.
6428 // Any attempt to resolve the exception specification of a defaulted default
6429 // constructor before the initializer is lexically complete will ultimately
6430 // come here at which point we can diagnose it.
6431 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
6432 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
6433 << OutermostClass << Field;
6434 Diag(Field->getEndLoc(),
6435 diag::note_default_member_initializer_not_yet_parsed);
6436 // Recover by marking the field invalid, unless we're in a SFINAE context.
6437 if (!isSFINAEContext())
6438 Field->setInvalidDecl();
6439 return ExprError();
6442 Sema::VariadicCallType
6443 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
6444 Expr *Fn) {
6445 if (Proto && Proto->isVariadic()) {
6446 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
6447 return VariadicConstructor;
6448 else if (Fn && Fn->getType()->isBlockPointerType())
6449 return VariadicBlock;
6450 else if (FDecl) {
6451 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6452 if (Method->isInstance())
6453 return VariadicMethod;
6454 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
6455 return VariadicMethod;
6456 return VariadicFunction;
6458 return VariadicDoesNotApply;
6461 namespace {
6462 class FunctionCallCCC final : public FunctionCallFilterCCC {
6463 public:
6464 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
6465 unsigned NumArgs, MemberExpr *ME)
6466 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
6467 FunctionName(FuncName) {}
6469 bool ValidateCandidate(const TypoCorrection &candidate) override {
6470 if (!candidate.getCorrectionSpecifier() ||
6471 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
6472 return false;
6475 return FunctionCallFilterCCC::ValidateCandidate(candidate);
6478 std::unique_ptr<CorrectionCandidateCallback> clone() override {
6479 return std::make_unique<FunctionCallCCC>(*this);
6482 private:
6483 const IdentifierInfo *const FunctionName;
6487 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
6488 FunctionDecl *FDecl,
6489 ArrayRef<Expr *> Args) {
6490 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
6491 DeclarationName FuncName = FDecl->getDeclName();
6492 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6494 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6495 if (TypoCorrection Corrected = S.CorrectTypo(
6496 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
6497 S.getScopeForContext(S.CurContext), nullptr, CCC,
6498 Sema::CTK_ErrorRecovery)) {
6499 if (NamedDecl *ND = Corrected.getFoundDecl()) {
6500 if (Corrected.isOverloaded()) {
6501 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
6502 OverloadCandidateSet::iterator Best;
6503 for (NamedDecl *CD : Corrected) {
6504 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
6505 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
6506 OCS);
6508 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
6509 case OR_Success:
6510 ND = Best->FoundDecl;
6511 Corrected.setCorrectionDecl(ND);
6512 break;
6513 default:
6514 break;
6517 ND = ND->getUnderlyingDecl();
6518 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
6519 return Corrected;
6522 return TypoCorrection();
6525 /// ConvertArgumentsForCall - Converts the arguments specified in
6526 /// Args/NumArgs to the parameter types of the function FDecl with
6527 /// function prototype Proto. Call is the call expression itself, and
6528 /// Fn is the function expression. For a C++ member function, this
6529 /// routine does not attempt to convert the object argument. Returns
6530 /// true if the call is ill-formed.
6531 bool
6532 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
6533 FunctionDecl *FDecl,
6534 const FunctionProtoType *Proto,
6535 ArrayRef<Expr *> Args,
6536 SourceLocation RParenLoc,
6537 bool IsExecConfig) {
6538 // Bail out early if calling a builtin with custom typechecking.
6539 if (FDecl)
6540 if (unsigned ID = FDecl->getBuiltinID())
6541 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
6542 return false;
6544 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6545 // assignment, to the types of the corresponding parameter, ...
6546 bool HasExplicitObjectParameter =
6547 FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
6548 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
6549 unsigned NumParams = Proto->getNumParams();
6550 bool Invalid = false;
6551 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6552 unsigned FnKind = Fn->getType()->isBlockPointerType()
6553 ? 1 /* block */
6554 : (IsExecConfig ? 3 /* kernel function (exec config) */
6555 : 0 /* function */);
6557 // If too few arguments are available (and we don't have default
6558 // arguments for the remaining parameters), don't make the call.
6559 if (Args.size() < NumParams) {
6560 if (Args.size() < MinArgs) {
6561 TypoCorrection TC;
6562 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6563 unsigned diag_id =
6564 MinArgs == NumParams && !Proto->isVariadic()
6565 ? diag::err_typecheck_call_too_few_args_suggest
6566 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6567 diagnoseTypo(
6568 TC, PDiag(diag_id)
6569 << FnKind << MinArgs - ExplicitObjectParameterOffset
6570 << static_cast<unsigned>(Args.size()) -
6571 ExplicitObjectParameterOffset
6572 << HasExplicitObjectParameter << TC.getCorrectionRange());
6573 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6574 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6575 ->getDeclName())
6576 Diag(RParenLoc,
6577 MinArgs == NumParams && !Proto->isVariadic()
6578 ? diag::err_typecheck_call_too_few_args_one
6579 : diag::err_typecheck_call_too_few_args_at_least_one)
6580 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6581 << HasExplicitObjectParameter << Fn->getSourceRange();
6582 else
6583 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6584 ? diag::err_typecheck_call_too_few_args
6585 : diag::err_typecheck_call_too_few_args_at_least)
6586 << FnKind << MinArgs - ExplicitObjectParameterOffset
6587 << static_cast<unsigned>(Args.size()) -
6588 ExplicitObjectParameterOffset
6589 << HasExplicitObjectParameter << Fn->getSourceRange();
6591 // Emit the location of the prototype.
6592 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6593 Diag(FDecl->getLocation(), diag::note_callee_decl)
6594 << FDecl << FDecl->getParametersSourceRange();
6596 return true;
6598 // We reserve space for the default arguments when we create
6599 // the call expression, before calling ConvertArgumentsForCall.
6600 assert((Call->getNumArgs() == NumParams) &&
6601 "We should have reserved space for the default arguments before!");
6604 // If too many are passed and not variadic, error on the extras and drop
6605 // them.
6606 if (Args.size() > NumParams) {
6607 if (!Proto->isVariadic()) {
6608 TypoCorrection TC;
6609 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6610 unsigned diag_id =
6611 MinArgs == NumParams && !Proto->isVariadic()
6612 ? diag::err_typecheck_call_too_many_args_suggest
6613 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6614 diagnoseTypo(
6615 TC, PDiag(diag_id)
6616 << FnKind << NumParams - ExplicitObjectParameterOffset
6617 << static_cast<unsigned>(Args.size()) -
6618 ExplicitObjectParameterOffset
6619 << HasExplicitObjectParameter << TC.getCorrectionRange());
6620 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6621 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6622 ->getDeclName())
6623 Diag(Args[NumParams]->getBeginLoc(),
6624 MinArgs == NumParams
6625 ? diag::err_typecheck_call_too_many_args_one
6626 : diag::err_typecheck_call_too_many_args_at_most_one)
6627 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6628 << static_cast<unsigned>(Args.size()) -
6629 ExplicitObjectParameterOffset
6630 << HasExplicitObjectParameter << Fn->getSourceRange()
6631 << SourceRange(Args[NumParams]->getBeginLoc(),
6632 Args.back()->getEndLoc());
6633 else
6634 Diag(Args[NumParams]->getBeginLoc(),
6635 MinArgs == NumParams
6636 ? diag::err_typecheck_call_too_many_args
6637 : diag::err_typecheck_call_too_many_args_at_most)
6638 << FnKind << NumParams - ExplicitObjectParameterOffset
6639 << static_cast<unsigned>(Args.size()) -
6640 ExplicitObjectParameterOffset
6641 << HasExplicitObjectParameter << Fn->getSourceRange()
6642 << SourceRange(Args[NumParams]->getBeginLoc(),
6643 Args.back()->getEndLoc());
6645 // Emit the location of the prototype.
6646 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6647 Diag(FDecl->getLocation(), diag::note_callee_decl)
6648 << FDecl << FDecl->getParametersSourceRange();
6650 // This deletes the extra arguments.
6651 Call->shrinkNumArgs(NumParams);
6652 return true;
6655 SmallVector<Expr *, 8> AllArgs;
6656 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6658 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
6659 AllArgs, CallType);
6660 if (Invalid)
6661 return true;
6662 unsigned TotalNumArgs = AllArgs.size();
6663 for (unsigned i = 0; i < TotalNumArgs; ++i)
6664 Call->setArg(i, AllArgs[i]);
6666 Call->computeDependence();
6667 return false;
6670 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6671 const FunctionProtoType *Proto,
6672 unsigned FirstParam, ArrayRef<Expr *> Args,
6673 SmallVectorImpl<Expr *> &AllArgs,
6674 VariadicCallType CallType, bool AllowExplicit,
6675 bool IsListInitialization) {
6676 unsigned NumParams = Proto->getNumParams();
6677 bool Invalid = false;
6678 size_t ArgIx = 0;
6679 // Continue to check argument types (even if we have too few/many args).
6680 for (unsigned i = FirstParam; i < NumParams; i++) {
6681 QualType ProtoArgType = Proto->getParamType(i);
6683 Expr *Arg;
6684 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6685 if (ArgIx < Args.size()) {
6686 Arg = Args[ArgIx++];
6688 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6689 diag::err_call_incomplete_argument, Arg))
6690 return true;
6692 // Strip the unbridged-cast placeholder expression off, if applicable.
6693 bool CFAudited = false;
6694 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6695 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6696 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6697 Arg = stripARCUnbridgedCast(Arg);
6698 else if (getLangOpts().ObjCAutoRefCount &&
6699 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6700 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6701 CFAudited = true;
6703 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6704 ProtoArgType->isBlockPointerType())
6705 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6706 BE->getBlockDecl()->setDoesNotEscape();
6708 InitializedEntity Entity =
6709 Param ? InitializedEntity::InitializeParameter(Context, Param,
6710 ProtoArgType)
6711 : InitializedEntity::InitializeParameter(
6712 Context, ProtoArgType, Proto->isParamConsumed(i));
6714 // Remember that parameter belongs to a CF audited API.
6715 if (CFAudited)
6716 Entity.setParameterCFAudited();
6718 ExprResult ArgE = PerformCopyInitialization(
6719 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6720 if (ArgE.isInvalid())
6721 return true;
6723 Arg = ArgE.getAs<Expr>();
6724 } else {
6725 assert(Param && "can't use default arguments without a known callee");
6727 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6728 if (ArgExpr.isInvalid())
6729 return true;
6731 Arg = ArgExpr.getAs<Expr>();
6734 // Check for array bounds violations for each argument to the call. This
6735 // check only triggers warnings when the argument isn't a more complex Expr
6736 // with its own checking, such as a BinaryOperator.
6737 CheckArrayAccess(Arg);
6739 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6740 CheckStaticArrayArgument(CallLoc, Param, Arg);
6742 AllArgs.push_back(Arg);
6745 // If this is a variadic call, handle args passed through "...".
6746 if (CallType != VariadicDoesNotApply) {
6747 // Assume that extern "C" functions with variadic arguments that
6748 // return __unknown_anytype aren't *really* variadic.
6749 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6750 FDecl->isExternC()) {
6751 for (Expr *A : Args.slice(ArgIx)) {
6752 QualType paramType; // ignored
6753 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6754 Invalid |= arg.isInvalid();
6755 AllArgs.push_back(arg.get());
6758 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6759 } else {
6760 for (Expr *A : Args.slice(ArgIx)) {
6761 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6762 Invalid |= Arg.isInvalid();
6763 AllArgs.push_back(Arg.get());
6767 // Check for array bounds violations.
6768 for (Expr *A : Args.slice(ArgIx))
6769 CheckArrayAccess(A);
6771 return Invalid;
6774 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6775 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6776 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6777 TL = DTL.getOriginalLoc();
6778 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6779 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6780 << ATL.getLocalSourceRange();
6783 /// CheckStaticArrayArgument - If the given argument corresponds to a static
6784 /// array parameter, check that it is non-null, and that if it is formed by
6785 /// array-to-pointer decay, the underlying array is sufficiently large.
6787 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6788 /// array type derivation, then for each call to the function, the value of the
6789 /// corresponding actual argument shall provide access to the first element of
6790 /// an array with at least as many elements as specified by the size expression.
6791 void
6792 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6793 ParmVarDecl *Param,
6794 const Expr *ArgExpr) {
6795 // Static array parameters are not supported in C++.
6796 if (!Param || getLangOpts().CPlusPlus)
6797 return;
6799 QualType OrigTy = Param->getOriginalType();
6801 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6802 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6803 return;
6805 if (ArgExpr->isNullPointerConstant(Context,
6806 Expr::NPC_NeverValueDependent)) {
6807 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6808 DiagnoseCalleeStaticArrayParam(*this, Param);
6809 return;
6812 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6813 if (!CAT)
6814 return;
6816 const ConstantArrayType *ArgCAT =
6817 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6818 if (!ArgCAT)
6819 return;
6821 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6822 ArgCAT->getElementType())) {
6823 if (ArgCAT->getSize().ult(CAT->getSize())) {
6824 Diag(CallLoc, diag::warn_static_array_too_small)
6825 << ArgExpr->getSourceRange()
6826 << (unsigned)ArgCAT->getSize().getZExtValue()
6827 << (unsigned)CAT->getSize().getZExtValue() << 0;
6828 DiagnoseCalleeStaticArrayParam(*this, Param);
6830 return;
6833 std::optional<CharUnits> ArgSize =
6834 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6835 std::optional<CharUnits> ParmSize =
6836 getASTContext().getTypeSizeInCharsIfKnown(CAT);
6837 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6838 Diag(CallLoc, diag::warn_static_array_too_small)
6839 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6840 << (unsigned)ParmSize->getQuantity() << 1;
6841 DiagnoseCalleeStaticArrayParam(*this, Param);
6845 /// Given a function expression of unknown-any type, try to rebuild it
6846 /// to have a function type.
6847 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6849 /// Is the given type a placeholder that we need to lower out
6850 /// immediately during argument processing?
6851 static bool isPlaceholderToRemoveAsArg(QualType type) {
6852 // Placeholders are never sugared.
6853 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6854 if (!placeholder) return false;
6856 switch (placeholder->getKind()) {
6857 // Ignore all the non-placeholder types.
6858 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6859 case BuiltinType::Id:
6860 #include "clang/Basic/OpenCLImageTypes.def"
6861 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6862 case BuiltinType::Id:
6863 #include "clang/Basic/OpenCLExtensionTypes.def"
6864 // In practice we'll never use this, since all SVE types are sugared
6865 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6866 #define SVE_TYPE(Name, Id, SingletonId) \
6867 case BuiltinType::Id:
6868 #include "clang/Basic/AArch64SVEACLETypes.def"
6869 #define PPC_VECTOR_TYPE(Name, Id, Size) \
6870 case BuiltinType::Id:
6871 #include "clang/Basic/PPCTypes.def"
6872 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6873 #include "clang/Basic/RISCVVTypes.def"
6874 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6875 #include "clang/Basic/WebAssemblyReferenceTypes.def"
6876 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6877 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6878 #include "clang/AST/BuiltinTypes.def"
6879 return false;
6881 // We cannot lower out overload sets; they might validly be resolved
6882 // by the call machinery.
6883 case BuiltinType::Overload:
6884 return false;
6886 // Unbridged casts in ARC can be handled in some call positions and
6887 // should be left in place.
6888 case BuiltinType::ARCUnbridgedCast:
6889 return false;
6891 // Pseudo-objects should be converted as soon as possible.
6892 case BuiltinType::PseudoObject:
6893 return true;
6895 // The debugger mode could theoretically but currently does not try
6896 // to resolve unknown-typed arguments based on known parameter types.
6897 case BuiltinType::UnknownAny:
6898 return true;
6900 // These are always invalid as call arguments and should be reported.
6901 case BuiltinType::BoundMember:
6902 case BuiltinType::BuiltinFn:
6903 case BuiltinType::IncompleteMatrixIdx:
6904 case BuiltinType::OMPArraySection:
6905 case BuiltinType::OMPArrayShaping:
6906 case BuiltinType::OMPIterator:
6907 return true;
6910 llvm_unreachable("bad builtin type kind");
6913 /// Check an argument list for placeholders that we won't try to
6914 /// handle later.
6915 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6916 // Apply this processing to all the arguments at once instead of
6917 // dying at the first failure.
6918 bool hasInvalid = false;
6919 for (size_t i = 0, e = args.size(); i != e; i++) {
6920 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6921 ExprResult result = S.CheckPlaceholderExpr(args[i]);
6922 if (result.isInvalid()) hasInvalid = true;
6923 else args[i] = result.get();
6926 return hasInvalid;
6929 /// If a builtin function has a pointer argument with no explicit address
6930 /// space, then it should be able to accept a pointer to any address
6931 /// space as input. In order to do this, we need to replace the
6932 /// standard builtin declaration with one that uses the same address space
6933 /// as the call.
6935 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6936 /// it does not contain any pointer arguments without
6937 /// an address space qualifer. Otherwise the rewritten
6938 /// FunctionDecl is returned.
6939 /// TODO: Handle pointer return types.
6940 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6941 FunctionDecl *FDecl,
6942 MultiExprArg ArgExprs) {
6944 QualType DeclType = FDecl->getType();
6945 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6947 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6948 ArgExprs.size() < FT->getNumParams())
6949 return nullptr;
6951 bool NeedsNewDecl = false;
6952 unsigned i = 0;
6953 SmallVector<QualType, 8> OverloadParams;
6955 for (QualType ParamType : FT->param_types()) {
6957 // Convert array arguments to pointer to simplify type lookup.
6958 ExprResult ArgRes =
6959 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6960 if (ArgRes.isInvalid())
6961 return nullptr;
6962 Expr *Arg = ArgRes.get();
6963 QualType ArgType = Arg->getType();
6964 if (!ParamType->isPointerType() || ParamType.hasAddressSpace() ||
6965 !ArgType->isPointerType() ||
6966 !ArgType->getPointeeType().hasAddressSpace() ||
6967 isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) {
6968 OverloadParams.push_back(ParamType);
6969 continue;
6972 QualType PointeeType = ParamType->getPointeeType();
6973 if (PointeeType.hasAddressSpace())
6974 continue;
6976 NeedsNewDecl = true;
6977 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6979 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6980 OverloadParams.push_back(Context.getPointerType(PointeeType));
6983 if (!NeedsNewDecl)
6984 return nullptr;
6986 FunctionProtoType::ExtProtoInfo EPI;
6987 EPI.Variadic = FT->isVariadic();
6988 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6989 OverloadParams, EPI);
6990 DeclContext *Parent = FDecl->getParent();
6991 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6992 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6993 FDecl->getIdentifier(), OverloadTy,
6994 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6995 false,
6996 /*hasPrototype=*/true);
6997 SmallVector<ParmVarDecl*, 16> Params;
6998 FT = cast<FunctionProtoType>(OverloadTy);
6999 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
7000 QualType ParamType = FT->getParamType(i);
7001 ParmVarDecl *Parm =
7002 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
7003 SourceLocation(), nullptr, ParamType,
7004 /*TInfo=*/nullptr, SC_None, nullptr);
7005 Parm->setScopeInfo(0, i);
7006 Params.push_back(Parm);
7008 OverloadDecl->setParams(Params);
7009 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
7010 return OverloadDecl;
7013 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
7014 FunctionDecl *Callee,
7015 MultiExprArg ArgExprs) {
7016 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
7017 // similar attributes) really don't like it when functions are called with an
7018 // invalid number of args.
7019 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
7020 /*PartialOverloading=*/false) &&
7021 !Callee->isVariadic())
7022 return;
7023 if (Callee->getMinRequiredArguments() > ArgExprs.size())
7024 return;
7026 if (const EnableIfAttr *Attr =
7027 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
7028 S.Diag(Fn->getBeginLoc(),
7029 isa<CXXMethodDecl>(Callee)
7030 ? diag::err_ovl_no_viable_member_function_in_call
7031 : diag::err_ovl_no_viable_function_in_call)
7032 << Callee << Callee->getSourceRange();
7033 S.Diag(Callee->getLocation(),
7034 diag::note_ovl_candidate_disabled_by_function_cond_attr)
7035 << Attr->getCond()->getSourceRange() << Attr->getMessage();
7036 return;
7040 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
7041 const UnresolvedMemberExpr *const UME, Sema &S) {
7043 const auto GetFunctionLevelDCIfCXXClass =
7044 [](Sema &S) -> const CXXRecordDecl * {
7045 const DeclContext *const DC = S.getFunctionLevelDeclContext();
7046 if (!DC || !DC->getParent())
7047 return nullptr;
7049 // If the call to some member function was made from within a member
7050 // function body 'M' return return 'M's parent.
7051 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
7052 return MD->getParent()->getCanonicalDecl();
7053 // else the call was made from within a default member initializer of a
7054 // class, so return the class.
7055 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
7056 return RD->getCanonicalDecl();
7057 return nullptr;
7059 // If our DeclContext is neither a member function nor a class (in the
7060 // case of a lambda in a default member initializer), we can't have an
7061 // enclosing 'this'.
7063 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
7064 if (!CurParentClass)
7065 return false;
7067 // The naming class for implicit member functions call is the class in which
7068 // name lookup starts.
7069 const CXXRecordDecl *const NamingClass =
7070 UME->getNamingClass()->getCanonicalDecl();
7071 assert(NamingClass && "Must have naming class even for implicit access");
7073 // If the unresolved member functions were found in a 'naming class' that is
7074 // related (either the same or derived from) to the class that contains the
7075 // member function that itself contained the implicit member access.
7077 return CurParentClass == NamingClass ||
7078 CurParentClass->isDerivedFrom(NamingClass);
7081 static void
7082 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
7083 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
7085 if (!UME)
7086 return;
7088 LambdaScopeInfo *const CurLSI = S.getCurLambda();
7089 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
7090 // already been captured, or if this is an implicit member function call (if
7091 // it isn't, an attempt to capture 'this' should already have been made).
7092 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
7093 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
7094 return;
7096 // Check if the naming class in which the unresolved members were found is
7097 // related (same as or is a base of) to the enclosing class.
7099 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
7100 return;
7103 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
7104 // If the enclosing function is not dependent, then this lambda is
7105 // capture ready, so if we can capture this, do so.
7106 if (!EnclosingFunctionCtx->isDependentContext()) {
7107 // If the current lambda and all enclosing lambdas can capture 'this' -
7108 // then go ahead and capture 'this' (since our unresolved overload set
7109 // contains at least one non-static member function).
7110 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
7111 S.CheckCXXThisCapture(CallLoc);
7112 } else if (S.CurContext->isDependentContext()) {
7113 // ... since this is an implicit member reference, that might potentially
7114 // involve a 'this' capture, mark 'this' for potential capture in
7115 // enclosing lambdas.
7116 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
7117 CurLSI->addPotentialThisCapture(CallLoc);
7121 // Once a call is fully resolved, warn for unqualified calls to specific
7122 // C++ standard functions, like move and forward.
7123 static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S,
7124 const CallExpr *Call) {
7125 // We are only checking unary move and forward so exit early here.
7126 if (Call->getNumArgs() != 1)
7127 return;
7129 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
7130 if (!E || isa<UnresolvedLookupExpr>(E))
7131 return;
7132 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
7133 if (!DRE || !DRE->getLocation().isValid())
7134 return;
7136 if (DRE->getQualifier())
7137 return;
7139 const FunctionDecl *FD = Call->getDirectCallee();
7140 if (!FD)
7141 return;
7143 // Only warn for some functions deemed more frequent or problematic.
7144 unsigned BuiltinID = FD->getBuiltinID();
7145 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
7146 return;
7148 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
7149 << FD->getQualifiedNameAsString()
7150 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
7153 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
7154 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7155 Expr *ExecConfig) {
7156 ExprResult Call =
7157 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
7158 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
7159 if (Call.isInvalid())
7160 return Call;
7162 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
7163 // language modes.
7164 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
7165 ULE && ULE->hasExplicitTemplateArgs() &&
7166 ULE->decls_begin() == ULE->decls_end()) {
7167 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
7168 ? diag::warn_cxx17_compat_adl_only_template_id
7169 : diag::ext_adl_only_template_id)
7170 << ULE->getName();
7173 if (LangOpts.OpenMP)
7174 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
7175 ExecConfig);
7176 if (LangOpts.CPlusPlus) {
7177 if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
7178 DiagnosedUnqualifiedCallsToStdFunctions(*this, CE);
7180 return Call;
7183 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
7184 /// This provides the location of the left/right parens and a list of comma
7185 /// locations.
7186 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
7187 MultiExprArg ArgExprs, SourceLocation RParenLoc,
7188 Expr *ExecConfig, bool IsExecConfig,
7189 bool AllowRecovery) {
7190 // Since this might be a postfix expression, get rid of ParenListExprs.
7191 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
7192 if (Result.isInvalid()) return ExprError();
7193 Fn = Result.get();
7195 if (checkArgsForPlaceholders(*this, ArgExprs))
7196 return ExprError();
7198 if (getLangOpts().CPlusPlus) {
7199 // If this is a pseudo-destructor expression, build the call immediately.
7200 if (isa<CXXPseudoDestructorExpr>(Fn)) {
7201 if (!ArgExprs.empty()) {
7202 // Pseudo-destructor calls should not have any arguments.
7203 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
7204 << FixItHint::CreateRemoval(
7205 SourceRange(ArgExprs.front()->getBeginLoc(),
7206 ArgExprs.back()->getEndLoc()));
7209 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
7210 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7212 if (Fn->getType() == Context.PseudoObjectTy) {
7213 ExprResult result = CheckPlaceholderExpr(Fn);
7214 if (result.isInvalid()) return ExprError();
7215 Fn = result.get();
7218 // Determine whether this is a dependent call inside a C++ template,
7219 // in which case we won't do any semantic analysis now.
7220 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
7221 if (ExecConfig) {
7222 return CUDAKernelCallExpr::Create(Context, Fn,
7223 cast<CallExpr>(ExecConfig), ArgExprs,
7224 Context.DependentTy, VK_PRValue,
7225 RParenLoc, CurFPFeatureOverrides());
7226 } else {
7228 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
7229 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
7230 Fn->getBeginLoc());
7232 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
7233 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7237 // Determine whether this is a call to an object (C++ [over.call.object]).
7238 if (Fn->getType()->isRecordType())
7239 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
7240 RParenLoc);
7242 if (Fn->getType() == Context.UnknownAnyTy) {
7243 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
7244 if (result.isInvalid()) return ExprError();
7245 Fn = result.get();
7248 if (Fn->getType() == Context.BoundMemberTy) {
7249 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
7250 RParenLoc, ExecConfig, IsExecConfig,
7251 AllowRecovery);
7255 // Check for overloaded calls. This can happen even in C due to extensions.
7256 if (Fn->getType() == Context.OverloadTy) {
7257 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
7259 // We aren't supposed to apply this logic if there's an '&' involved.
7260 if (!find.HasFormOfMemberPointer) {
7261 if (Expr::hasAnyTypeDependentArguments(ArgExprs))
7262 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
7263 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7264 OverloadExpr *ovl = find.Expression;
7265 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
7266 return BuildOverloadedCallExpr(
7267 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
7268 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
7269 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
7270 RParenLoc, ExecConfig, IsExecConfig,
7271 AllowRecovery);
7275 // If we're directly calling a function, get the appropriate declaration.
7276 if (Fn->getType() == Context.UnknownAnyTy) {
7277 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
7278 if (result.isInvalid()) return ExprError();
7279 Fn = result.get();
7282 Expr *NakedFn = Fn->IgnoreParens();
7284 bool CallingNDeclIndirectly = false;
7285 NamedDecl *NDecl = nullptr;
7286 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
7287 if (UnOp->getOpcode() == UO_AddrOf) {
7288 CallingNDeclIndirectly = true;
7289 NakedFn = UnOp->getSubExpr()->IgnoreParens();
7293 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
7294 NDecl = DRE->getDecl();
7296 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
7297 if (FDecl && FDecl->getBuiltinID()) {
7298 // Rewrite the function decl for this builtin by replacing parameters
7299 // with no explicit address space with the address space of the arguments
7300 // in ArgExprs.
7301 if ((FDecl =
7302 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
7303 NDecl = FDecl;
7304 Fn = DeclRefExpr::Create(
7305 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
7306 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
7307 nullptr, DRE->isNonOdrUse());
7310 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
7311 NDecl = ME->getMemberDecl();
7313 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
7314 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
7315 FD, /*Complain=*/true, Fn->getBeginLoc()))
7316 return ExprError();
7318 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
7320 // If this expression is a call to a builtin function in HIP device
7321 // compilation, allow a pointer-type argument to default address space to be
7322 // passed as a pointer-type parameter to a non-default address space.
7323 // If Arg is declared in the default address space and Param is declared
7324 // in a non-default address space, perform an implicit address space cast to
7325 // the parameter type.
7326 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
7327 FD->getBuiltinID()) {
7328 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
7329 ParmVarDecl *Param = FD->getParamDecl(Idx);
7330 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
7331 !ArgExprs[Idx]->getType()->isPointerType())
7332 continue;
7334 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
7335 auto ArgTy = ArgExprs[Idx]->getType();
7336 auto ArgPtTy = ArgTy->getPointeeType();
7337 auto ArgAS = ArgPtTy.getAddressSpace();
7339 // Add address space cast if target address spaces are different
7340 bool NeedImplicitASC =
7341 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
7342 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
7343 // or from specific AS which has target AS matching that of Param.
7344 getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));
7345 if (!NeedImplicitASC)
7346 continue;
7348 // First, ensure that the Arg is an RValue.
7349 if (ArgExprs[Idx]->isGLValue()) {
7350 ArgExprs[Idx] = ImplicitCastExpr::Create(
7351 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
7352 nullptr, VK_PRValue, FPOptionsOverride());
7355 // Construct a new arg type with address space of Param
7356 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
7357 ArgPtQuals.setAddressSpace(ParamAS);
7358 auto NewArgPtTy =
7359 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
7360 auto NewArgTy =
7361 Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
7362 ArgTy.getQualifiers());
7364 // Finally perform an implicit address space cast
7365 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
7366 CK_AddressSpaceConversion)
7367 .get();
7372 if (Context.isDependenceAllowed() &&
7373 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
7374 assert(!getLangOpts().CPlusPlus);
7375 assert((Fn->containsErrors() ||
7376 llvm::any_of(ArgExprs,
7377 [](clang::Expr *E) { return E->containsErrors(); })) &&
7378 "should only occur in error-recovery path.");
7379 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
7380 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7382 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
7383 ExecConfig, IsExecConfig);
7386 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
7387 // with the specified CallArgs
7388 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
7389 MultiExprArg CallArgs) {
7390 StringRef Name = Context.BuiltinInfo.getName(Id);
7391 LookupResult R(*this, &Context.Idents.get(Name), Loc,
7392 Sema::LookupOrdinaryName);
7393 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
7395 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
7396 assert(BuiltInDecl && "failed to find builtin declaration");
7398 ExprResult DeclRef =
7399 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
7400 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
7402 ExprResult Call =
7403 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
7405 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
7406 return Call.get();
7409 /// Parse a __builtin_astype expression.
7411 /// __builtin_astype( value, dst type )
7413 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
7414 SourceLocation BuiltinLoc,
7415 SourceLocation RParenLoc) {
7416 QualType DstTy = GetTypeFromParser(ParsedDestTy);
7417 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
7420 /// Create a new AsTypeExpr node (bitcast) from the arguments.
7421 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
7422 SourceLocation BuiltinLoc,
7423 SourceLocation RParenLoc) {
7424 ExprValueKind VK = VK_PRValue;
7425 ExprObjectKind OK = OK_Ordinary;
7426 QualType SrcTy = E->getType();
7427 if (!SrcTy->isDependentType() &&
7428 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
7429 return ExprError(
7430 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
7431 << DestTy << SrcTy << E->getSourceRange());
7432 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7435 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
7436 /// provided arguments.
7438 /// __builtin_convertvector( value, dst type )
7440 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
7441 SourceLocation BuiltinLoc,
7442 SourceLocation RParenLoc) {
7443 TypeSourceInfo *TInfo;
7444 GetTypeFromParser(ParsedDestTy, &TInfo);
7445 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7448 /// BuildResolvedCallExpr - Build a call to a resolved expression,
7449 /// i.e. an expression not of \p OverloadTy. The expression should
7450 /// unary-convert to an expression of function-pointer or
7451 /// block-pointer type.
7453 /// \param NDecl the declaration being called, if available
7454 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
7455 SourceLocation LParenLoc,
7456 ArrayRef<Expr *> Args,
7457 SourceLocation RParenLoc, Expr *Config,
7458 bool IsExecConfig, ADLCallKind UsesADL) {
7459 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
7460 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7462 // Functions with 'interrupt' attribute cannot be called directly.
7463 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
7464 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
7465 return ExprError();
7468 // Interrupt handlers don't save off the VFP regs automatically on ARM,
7469 // so there's some risk when calling out to non-interrupt handler functions
7470 // that the callee might not preserve them. This is easy to diagnose here,
7471 // but can be very challenging to debug.
7472 // Likewise, X86 interrupt handlers may only call routines with attribute
7473 // no_caller_saved_registers since there is no efficient way to
7474 // save and restore the non-GPR state.
7475 if (auto *Caller = getCurFunctionDecl()) {
7476 if (Caller->hasAttr<ARMInterruptAttr>()) {
7477 bool VFP = Context.getTargetInfo().hasFeature("vfp");
7478 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
7479 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
7480 if (FDecl)
7481 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7484 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
7485 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
7486 const TargetInfo &TI = Context.getTargetInfo();
7487 bool HasNonGPRRegisters =
7488 TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
7489 if (HasNonGPRRegisters &&
7490 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
7491 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
7492 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
7493 if (FDecl)
7494 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7499 // Promote the function operand.
7500 // We special-case function promotion here because we only allow promoting
7501 // builtin functions to function pointers in the callee of a call.
7502 ExprResult Result;
7503 QualType ResultTy;
7504 if (BuiltinID &&
7505 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
7506 // Extract the return type from the (builtin) function pointer type.
7507 // FIXME Several builtins still have setType in
7508 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7509 // Builtins.def to ensure they are correct before removing setType calls.
7510 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
7511 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
7512 ResultTy = FDecl->getCallResultType();
7513 } else {
7514 Result = CallExprUnaryConversions(Fn);
7515 ResultTy = Context.BoolTy;
7517 if (Result.isInvalid())
7518 return ExprError();
7519 Fn = Result.get();
7521 // Check for a valid function type, but only if it is not a builtin which
7522 // requires custom type checking. These will be handled by
7523 // CheckBuiltinFunctionCall below just after creation of the call expression.
7524 const FunctionType *FuncT = nullptr;
7525 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7526 retry:
7527 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7528 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7529 // have type pointer to function".
7530 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7531 if (!FuncT)
7532 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7533 << Fn->getType() << Fn->getSourceRange());
7534 } else if (const BlockPointerType *BPT =
7535 Fn->getType()->getAs<BlockPointerType>()) {
7536 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7537 } else {
7538 // Handle calls to expressions of unknown-any type.
7539 if (Fn->getType() == Context.UnknownAnyTy) {
7540 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
7541 if (rewrite.isInvalid())
7542 return ExprError();
7543 Fn = rewrite.get();
7544 goto retry;
7547 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7548 << Fn->getType() << Fn->getSourceRange());
7552 // Get the number of parameters in the function prototype, if any.
7553 // We will allocate space for max(Args.size(), NumParams) arguments
7554 // in the call expression.
7555 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
7556 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7558 CallExpr *TheCall;
7559 if (Config) {
7560 assert(UsesADL == ADLCallKind::NotADL &&
7561 "CUDAKernelCallExpr should not use ADL");
7562 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
7563 Args, ResultTy, VK_PRValue, RParenLoc,
7564 CurFPFeatureOverrides(), NumParams);
7565 } else {
7566 TheCall =
7567 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7568 CurFPFeatureOverrides(), NumParams, UsesADL);
7571 if (!Context.isDependenceAllowed()) {
7572 // Forget about the nulled arguments since typo correction
7573 // do not handle them well.
7574 TheCall->shrinkNumArgs(Args.size());
7575 // C cannot always handle TypoExpr nodes in builtin calls and direct
7576 // function calls as their argument checking don't necessarily handle
7577 // dependent types properly, so make sure any TypoExprs have been
7578 // dealt with.
7579 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
7580 if (!Result.isUsable()) return ExprError();
7581 CallExpr *TheOldCall = TheCall;
7582 TheCall = dyn_cast<CallExpr>(Result.get());
7583 bool CorrectedTypos = TheCall != TheOldCall;
7584 if (!TheCall) return Result;
7585 Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
7587 // A new call expression node was created if some typos were corrected.
7588 // However it may not have been constructed with enough storage. In this
7589 // case, rebuild the node with enough storage. The waste of space is
7590 // immaterial since this only happens when some typos were corrected.
7591 if (CorrectedTypos && Args.size() < NumParams) {
7592 if (Config)
7593 TheCall = CUDAKernelCallExpr::Create(
7594 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
7595 RParenLoc, CurFPFeatureOverrides(), NumParams);
7596 else
7597 TheCall =
7598 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7599 CurFPFeatureOverrides(), NumParams, UsesADL);
7601 // We can now handle the nulled arguments for the default arguments.
7602 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
7605 // Bail out early if calling a builtin with custom type checking.
7606 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
7607 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7609 if (getLangOpts().CUDA) {
7610 if (Config) {
7611 // CUDA: Kernel calls must be to global functions
7612 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7613 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7614 << FDecl << Fn->getSourceRange());
7616 // CUDA: Kernel function must have 'void' return type
7617 if (!FuncT->getReturnType()->isVoidType() &&
7618 !FuncT->getReturnType()->getAs<AutoType>() &&
7619 !FuncT->getReturnType()->isInstantiationDependentType())
7620 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7621 << Fn->getType() << Fn->getSourceRange());
7622 } else {
7623 // CUDA: Calls to global functions must be configured
7624 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7625 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7626 << FDecl << Fn->getSourceRange());
7630 // Check for a valid return type
7631 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7632 FDecl))
7633 return ExprError();
7635 // We know the result type of the call, set it.
7636 TheCall->setType(FuncT->getCallResultType(Context));
7637 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
7639 // WebAssembly tables can't be used as arguments.
7640 if (Context.getTargetInfo().getTriple().isWasm()) {
7641 for (const Expr *Arg : Args) {
7642 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7643 return ExprError(Diag(Arg->getExprLoc(),
7644 diag::err_wasm_table_as_function_parameter));
7649 if (Proto) {
7650 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7651 IsExecConfig))
7652 return ExprError();
7653 } else {
7654 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7656 if (FDecl) {
7657 // Check if we have too few/too many template arguments, based
7658 // on our knowledge of the function definition.
7659 const FunctionDecl *Def = nullptr;
7660 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7661 Proto = Def->getType()->getAs<FunctionProtoType>();
7662 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7663 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7664 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7667 // If the function we're calling isn't a function prototype, but we have
7668 // a function prototype from a prior declaratiom, use that prototype.
7669 if (!FDecl->hasPrototype())
7670 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7673 // If we still haven't found a prototype to use but there are arguments to
7674 // the call, diagnose this as calling a function without a prototype.
7675 // However, if we found a function declaration, check to see if
7676 // -Wdeprecated-non-prototype was disabled where the function was declared.
7677 // If so, we will silence the diagnostic here on the assumption that this
7678 // interface is intentional and the user knows what they're doing. We will
7679 // also silence the diagnostic if there is a function declaration but it
7680 // was implicitly defined (the user already gets diagnostics about the
7681 // creation of the implicit function declaration, so the additional warning
7682 // is not helpful).
7683 if (!Proto && !Args.empty() &&
7684 (!FDecl || (!FDecl->isImplicit() &&
7685 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7686 FDecl->getLocation()))))
7687 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7688 << (FDecl != nullptr) << FDecl;
7690 // Promote the arguments (C99 6.5.2.2p6).
7691 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7692 Expr *Arg = Args[i];
7694 if (Proto && i < Proto->getNumParams()) {
7695 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7696 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7697 ExprResult ArgE =
7698 PerformCopyInitialization(Entity, SourceLocation(), Arg);
7699 if (ArgE.isInvalid())
7700 return true;
7702 Arg = ArgE.getAs<Expr>();
7704 } else {
7705 ExprResult ArgE = DefaultArgumentPromotion(Arg);
7707 if (ArgE.isInvalid())
7708 return true;
7710 Arg = ArgE.getAs<Expr>();
7713 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7714 diag::err_call_incomplete_argument, Arg))
7715 return ExprError();
7717 TheCall->setArg(i, Arg);
7719 TheCall->computeDependence();
7722 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7723 if (Method->isImplicitObjectMemberFunction())
7724 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7725 << Fn->getSourceRange() << 0);
7727 // Check for sentinels
7728 if (NDecl)
7729 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7731 // Warn for unions passing across security boundary (CMSE).
7732 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7733 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7734 if (const auto *RT =
7735 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7736 if (RT->getDecl()->isOrContainsUnion())
7737 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7738 << 0 << i;
7743 // Do special checking on direct calls to functions.
7744 if (FDecl) {
7745 if (CheckFunctionCall(FDecl, TheCall, Proto))
7746 return ExprError();
7748 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7750 if (BuiltinID)
7751 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7752 } else if (NDecl) {
7753 if (CheckPointerCall(NDecl, TheCall, Proto))
7754 return ExprError();
7755 } else {
7756 if (CheckOtherCall(TheCall, Proto))
7757 return ExprError();
7760 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7763 ExprResult
7764 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7765 SourceLocation RParenLoc, Expr *InitExpr) {
7766 assert(Ty && "ActOnCompoundLiteral(): missing type");
7767 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7769 TypeSourceInfo *TInfo;
7770 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7771 if (!TInfo)
7772 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7774 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7777 ExprResult
7778 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7779 SourceLocation RParenLoc, Expr *LiteralExpr) {
7780 QualType literalType = TInfo->getType();
7782 if (literalType->isArrayType()) {
7783 if (RequireCompleteSizedType(
7784 LParenLoc, Context.getBaseElementType(literalType),
7785 diag::err_array_incomplete_or_sizeless_type,
7786 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7787 return ExprError();
7788 if (literalType->isVariableArrayType()) {
7789 // C23 6.7.10p4: An entity of variable length array type shall not be
7790 // initialized except by an empty initializer.
7792 // The C extension warnings are issued from ParseBraceInitializer() and
7793 // do not need to be issued here. However, we continue to issue an error
7794 // in the case there are initializers or we are compiling C++. We allow
7795 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7796 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7797 // FIXME: should we allow this construct in C++ when it makes sense to do
7798 // so?
7799 std::optional<unsigned> NumInits;
7800 if (const auto *ILE = dyn_cast<InitListExpr>(LiteralExpr))
7801 NumInits = ILE->getNumInits();
7802 if ((LangOpts.CPlusPlus || NumInits.value_or(0)) &&
7803 !tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7804 diag::err_variable_object_no_init))
7805 return ExprError();
7807 } else if (!literalType->isDependentType() &&
7808 RequireCompleteType(LParenLoc, literalType,
7809 diag::err_typecheck_decl_incomplete_type,
7810 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7811 return ExprError();
7813 InitializedEntity Entity
7814 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
7815 InitializationKind Kind
7816 = InitializationKind::CreateCStyleCast(LParenLoc,
7817 SourceRange(LParenLoc, RParenLoc),
7818 /*InitList=*/true);
7819 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7820 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7821 &literalType);
7822 if (Result.isInvalid())
7823 return ExprError();
7824 LiteralExpr = Result.get();
7826 bool isFileScope = !CurContext->isFunctionOrMethod();
7828 // In C, compound literals are l-values for some reason.
7829 // For GCC compatibility, in C++, file-scope array compound literals with
7830 // constant initializers are also l-values, and compound literals are
7831 // otherwise prvalues.
7833 // (GCC also treats C++ list-initialized file-scope array prvalues with
7834 // constant initializers as l-values, but that's non-conforming, so we don't
7835 // follow it there.)
7837 // FIXME: It would be better to handle the lvalue cases as materializing and
7838 // lifetime-extending a temporary object, but our materialized temporaries
7839 // representation only supports lifetime extension from a variable, not "out
7840 // of thin air".
7841 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7842 // is bound to the result of applying array-to-pointer decay to the compound
7843 // literal.
7844 // FIXME: GCC supports compound literals of reference type, which should
7845 // obviously have a value kind derived from the kind of reference involved.
7846 ExprValueKind VK =
7847 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7848 ? VK_PRValue
7849 : VK_LValue;
7851 if (isFileScope)
7852 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7853 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7854 Expr *Init = ILE->getInit(i);
7855 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7858 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7859 VK, LiteralExpr, isFileScope);
7860 if (isFileScope) {
7861 if (!LiteralExpr->isTypeDependent() &&
7862 !LiteralExpr->isValueDependent() &&
7863 !literalType->isDependentType()) // C99 6.5.2.5p3
7864 if (CheckForConstantInitializer(LiteralExpr, literalType))
7865 return ExprError();
7866 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7867 literalType.getAddressSpace() != LangAS::Default) {
7868 // Embedded-C extensions to C99 6.5.2.5:
7869 // "If the compound literal occurs inside the body of a function, the
7870 // type name shall not be qualified by an address-space qualifier."
7871 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7872 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7873 return ExprError();
7876 if (!isFileScope && !getLangOpts().CPlusPlus) {
7877 // Compound literals that have automatic storage duration are destroyed at
7878 // the end of the scope in C; in C++, they're just temporaries.
7880 // Emit diagnostics if it is or contains a C union type that is non-trivial
7881 // to destruct.
7882 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7883 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7884 NTCUC_CompoundLiteral, NTCUK_Destruct);
7886 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7887 if (literalType.isDestructedType()) {
7888 Cleanup.setExprNeedsCleanups(true);
7889 ExprCleanupObjects.push_back(E);
7890 getCurFunction()->setHasBranchProtectedScope();
7894 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7895 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7896 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7897 E->getInitializer()->getExprLoc());
7899 return MaybeBindToTemporary(E);
7902 ExprResult
7903 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7904 SourceLocation RBraceLoc) {
7905 // Only produce each kind of designated initialization diagnostic once.
7906 SourceLocation FirstDesignator;
7907 bool DiagnosedArrayDesignator = false;
7908 bool DiagnosedNestedDesignator = false;
7909 bool DiagnosedMixedDesignator = false;
7911 // Check that any designated initializers are syntactically valid in the
7912 // current language mode.
7913 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7914 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7915 if (FirstDesignator.isInvalid())
7916 FirstDesignator = DIE->getBeginLoc();
7918 if (!getLangOpts().CPlusPlus)
7919 break;
7921 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7922 DiagnosedNestedDesignator = true;
7923 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7924 << DIE->getDesignatorsSourceRange();
7927 for (auto &Desig : DIE->designators()) {
7928 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7929 DiagnosedArrayDesignator = true;
7930 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7931 << Desig.getSourceRange();
7935 if (!DiagnosedMixedDesignator &&
7936 !isa<DesignatedInitExpr>(InitArgList[0])) {
7937 DiagnosedMixedDesignator = true;
7938 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7939 << DIE->getSourceRange();
7940 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7941 << InitArgList[0]->getSourceRange();
7943 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7944 isa<DesignatedInitExpr>(InitArgList[0])) {
7945 DiagnosedMixedDesignator = true;
7946 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7947 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7948 << DIE->getSourceRange();
7949 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7950 << InitArgList[I]->getSourceRange();
7954 if (FirstDesignator.isValid()) {
7955 // Only diagnose designated initiaization as a C++20 extension if we didn't
7956 // already diagnose use of (non-C++20) C99 designator syntax.
7957 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7958 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7959 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7960 ? diag::warn_cxx17_compat_designated_init
7961 : diag::ext_cxx_designated_init);
7962 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7963 Diag(FirstDesignator, diag::ext_designated_init);
7967 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7970 ExprResult
7971 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7972 SourceLocation RBraceLoc) {
7973 // Semantic analysis for initializers is done by ActOnDeclarator() and
7974 // CheckInitializer() - it requires knowledge of the object being initialized.
7976 // Immediately handle non-overload placeholders. Overloads can be
7977 // resolved contextually, but everything else here can't.
7978 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7979 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7980 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7982 // Ignore failures; dropping the entire initializer list because
7983 // of one failure would be terrible for indexing/etc.
7984 if (result.isInvalid()) continue;
7986 InitArgList[I] = result.get();
7990 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7991 RBraceLoc);
7992 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7993 return E;
7996 /// Do an explicit extend of the given block pointer if we're in ARC.
7997 void Sema::maybeExtendBlockObject(ExprResult &E) {
7998 assert(E.get()->getType()->isBlockPointerType());
7999 assert(E.get()->isPRValue());
8001 // Only do this in an r-value context.
8002 if (!getLangOpts().ObjCAutoRefCount) return;
8004 E = ImplicitCastExpr::Create(
8005 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
8006 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
8007 Cleanup.setExprNeedsCleanups(true);
8010 /// Prepare a conversion of the given expression to an ObjC object
8011 /// pointer type.
8012 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
8013 QualType type = E.get()->getType();
8014 if (type->isObjCObjectPointerType()) {
8015 return CK_BitCast;
8016 } else if (type->isBlockPointerType()) {
8017 maybeExtendBlockObject(E);
8018 return CK_BlockPointerToObjCPointerCast;
8019 } else {
8020 assert(type->isPointerType());
8021 return CK_CPointerToObjCPointerCast;
8025 /// Prepares for a scalar cast, performing all the necessary stages
8026 /// except the final cast and returning the kind required.
8027 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
8028 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
8029 // Also, callers should have filtered out the invalid cases with
8030 // pointers. Everything else should be possible.
8032 QualType SrcTy = Src.get()->getType();
8033 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
8034 return CK_NoOp;
8036 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
8037 case Type::STK_MemberPointer:
8038 llvm_unreachable("member pointer type in C");
8040 case Type::STK_CPointer:
8041 case Type::STK_BlockPointer:
8042 case Type::STK_ObjCObjectPointer:
8043 switch (DestTy->getScalarTypeKind()) {
8044 case Type::STK_CPointer: {
8045 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
8046 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
8047 if (SrcAS != DestAS)
8048 return CK_AddressSpaceConversion;
8049 if (Context.hasCvrSimilarType(SrcTy, DestTy))
8050 return CK_NoOp;
8051 return CK_BitCast;
8053 case Type::STK_BlockPointer:
8054 return (SrcKind == Type::STK_BlockPointer
8055 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
8056 case Type::STK_ObjCObjectPointer:
8057 if (SrcKind == Type::STK_ObjCObjectPointer)
8058 return CK_BitCast;
8059 if (SrcKind == Type::STK_CPointer)
8060 return CK_CPointerToObjCPointerCast;
8061 maybeExtendBlockObject(Src);
8062 return CK_BlockPointerToObjCPointerCast;
8063 case Type::STK_Bool:
8064 return CK_PointerToBoolean;
8065 case Type::STK_Integral:
8066 return CK_PointerToIntegral;
8067 case Type::STK_Floating:
8068 case Type::STK_FloatingComplex:
8069 case Type::STK_IntegralComplex:
8070 case Type::STK_MemberPointer:
8071 case Type::STK_FixedPoint:
8072 llvm_unreachable("illegal cast from pointer");
8074 llvm_unreachable("Should have returned before this");
8076 case Type::STK_FixedPoint:
8077 switch (DestTy->getScalarTypeKind()) {
8078 case Type::STK_FixedPoint:
8079 return CK_FixedPointCast;
8080 case Type::STK_Bool:
8081 return CK_FixedPointToBoolean;
8082 case Type::STK_Integral:
8083 return CK_FixedPointToIntegral;
8084 case Type::STK_Floating:
8085 return CK_FixedPointToFloating;
8086 case Type::STK_IntegralComplex:
8087 case Type::STK_FloatingComplex:
8088 Diag(Src.get()->getExprLoc(),
8089 diag::err_unimplemented_conversion_with_fixed_point_type)
8090 << DestTy;
8091 return CK_IntegralCast;
8092 case Type::STK_CPointer:
8093 case Type::STK_ObjCObjectPointer:
8094 case Type::STK_BlockPointer:
8095 case Type::STK_MemberPointer:
8096 llvm_unreachable("illegal cast to pointer type");
8098 llvm_unreachable("Should have returned before this");
8100 case Type::STK_Bool: // casting from bool is like casting from an integer
8101 case Type::STK_Integral:
8102 switch (DestTy->getScalarTypeKind()) {
8103 case Type::STK_CPointer:
8104 case Type::STK_ObjCObjectPointer:
8105 case Type::STK_BlockPointer:
8106 if (Src.get()->isNullPointerConstant(Context,
8107 Expr::NPC_ValueDependentIsNull))
8108 return CK_NullToPointer;
8109 return CK_IntegralToPointer;
8110 case Type::STK_Bool:
8111 return CK_IntegralToBoolean;
8112 case Type::STK_Integral:
8113 return CK_IntegralCast;
8114 case Type::STK_Floating:
8115 return CK_IntegralToFloating;
8116 case Type::STK_IntegralComplex:
8117 Src = ImpCastExprToType(Src.get(),
8118 DestTy->castAs<ComplexType>()->getElementType(),
8119 CK_IntegralCast);
8120 return CK_IntegralRealToComplex;
8121 case Type::STK_FloatingComplex:
8122 Src = ImpCastExprToType(Src.get(),
8123 DestTy->castAs<ComplexType>()->getElementType(),
8124 CK_IntegralToFloating);
8125 return CK_FloatingRealToComplex;
8126 case Type::STK_MemberPointer:
8127 llvm_unreachable("member pointer type in C");
8128 case Type::STK_FixedPoint:
8129 return CK_IntegralToFixedPoint;
8131 llvm_unreachable("Should have returned before this");
8133 case Type::STK_Floating:
8134 switch (DestTy->getScalarTypeKind()) {
8135 case Type::STK_Floating:
8136 return CK_FloatingCast;
8137 case Type::STK_Bool:
8138 return CK_FloatingToBoolean;
8139 case Type::STK_Integral:
8140 return CK_FloatingToIntegral;
8141 case Type::STK_FloatingComplex:
8142 Src = ImpCastExprToType(Src.get(),
8143 DestTy->castAs<ComplexType>()->getElementType(),
8144 CK_FloatingCast);
8145 return CK_FloatingRealToComplex;
8146 case Type::STK_IntegralComplex:
8147 Src = ImpCastExprToType(Src.get(),
8148 DestTy->castAs<ComplexType>()->getElementType(),
8149 CK_FloatingToIntegral);
8150 return CK_IntegralRealToComplex;
8151 case Type::STK_CPointer:
8152 case Type::STK_ObjCObjectPointer:
8153 case Type::STK_BlockPointer:
8154 llvm_unreachable("valid float->pointer cast?");
8155 case Type::STK_MemberPointer:
8156 llvm_unreachable("member pointer type in C");
8157 case Type::STK_FixedPoint:
8158 return CK_FloatingToFixedPoint;
8160 llvm_unreachable("Should have returned before this");
8162 case Type::STK_FloatingComplex:
8163 switch (DestTy->getScalarTypeKind()) {
8164 case Type::STK_FloatingComplex:
8165 return CK_FloatingComplexCast;
8166 case Type::STK_IntegralComplex:
8167 return CK_FloatingComplexToIntegralComplex;
8168 case Type::STK_Floating: {
8169 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
8170 if (Context.hasSameType(ET, DestTy))
8171 return CK_FloatingComplexToReal;
8172 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
8173 return CK_FloatingCast;
8175 case Type::STK_Bool:
8176 return CK_FloatingComplexToBoolean;
8177 case Type::STK_Integral:
8178 Src = ImpCastExprToType(Src.get(),
8179 SrcTy->castAs<ComplexType>()->getElementType(),
8180 CK_FloatingComplexToReal);
8181 return CK_FloatingToIntegral;
8182 case Type::STK_CPointer:
8183 case Type::STK_ObjCObjectPointer:
8184 case Type::STK_BlockPointer:
8185 llvm_unreachable("valid complex float->pointer cast?");
8186 case Type::STK_MemberPointer:
8187 llvm_unreachable("member pointer type in C");
8188 case Type::STK_FixedPoint:
8189 Diag(Src.get()->getExprLoc(),
8190 diag::err_unimplemented_conversion_with_fixed_point_type)
8191 << SrcTy;
8192 return CK_IntegralCast;
8194 llvm_unreachable("Should have returned before this");
8196 case Type::STK_IntegralComplex:
8197 switch (DestTy->getScalarTypeKind()) {
8198 case Type::STK_FloatingComplex:
8199 return CK_IntegralComplexToFloatingComplex;
8200 case Type::STK_IntegralComplex:
8201 return CK_IntegralComplexCast;
8202 case Type::STK_Integral: {
8203 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
8204 if (Context.hasSameType(ET, DestTy))
8205 return CK_IntegralComplexToReal;
8206 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
8207 return CK_IntegralCast;
8209 case Type::STK_Bool:
8210 return CK_IntegralComplexToBoolean;
8211 case Type::STK_Floating:
8212 Src = ImpCastExprToType(Src.get(),
8213 SrcTy->castAs<ComplexType>()->getElementType(),
8214 CK_IntegralComplexToReal);
8215 return CK_IntegralToFloating;
8216 case Type::STK_CPointer:
8217 case Type::STK_ObjCObjectPointer:
8218 case Type::STK_BlockPointer:
8219 llvm_unreachable("valid complex int->pointer cast?");
8220 case Type::STK_MemberPointer:
8221 llvm_unreachable("member pointer type in C");
8222 case Type::STK_FixedPoint:
8223 Diag(Src.get()->getExprLoc(),
8224 diag::err_unimplemented_conversion_with_fixed_point_type)
8225 << SrcTy;
8226 return CK_IntegralCast;
8228 llvm_unreachable("Should have returned before this");
8231 llvm_unreachable("Unhandled scalar cast");
8234 static bool breakDownVectorType(QualType type, uint64_t &len,
8235 QualType &eltType) {
8236 // Vectors are simple.
8237 if (const VectorType *vecType = type->getAs<VectorType>()) {
8238 len = vecType->getNumElements();
8239 eltType = vecType->getElementType();
8240 assert(eltType->isScalarType());
8241 return true;
8244 // We allow lax conversion to and from non-vector types, but only if
8245 // they're real types (i.e. non-complex, non-pointer scalar types).
8246 if (!type->isRealType()) return false;
8248 len = 1;
8249 eltType = type;
8250 return true;
8253 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
8254 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
8255 /// allowed?
8257 /// This will also return false if the two given types do not make sense from
8258 /// the perspective of SVE bitcasts.
8259 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
8260 assert(srcTy->isVectorType() || destTy->isVectorType());
8262 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
8263 if (!FirstType->isSVESizelessBuiltinType())
8264 return false;
8266 const auto *VecTy = SecondType->getAs<VectorType>();
8267 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
8270 return ValidScalableConversion(srcTy, destTy) ||
8271 ValidScalableConversion(destTy, srcTy);
8274 /// Are the two types RVV-bitcast-compatible types? I.e. is bitcasting from the
8275 /// first RVV type (e.g. an RVV scalable type) to the second type (e.g. an RVV
8276 /// VLS type) allowed?
8278 /// This will also return false if the two given types do not make sense from
8279 /// the perspective of RVV bitcasts.
8280 bool Sema::isValidRVVBitcast(QualType srcTy, QualType destTy) {
8281 assert(srcTy->isVectorType() || destTy->isVectorType());
8283 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
8284 if (!FirstType->isRVVSizelessBuiltinType())
8285 return false;
8287 const auto *VecTy = SecondType->getAs<VectorType>();
8288 return VecTy && VecTy->getVectorKind() == VectorKind::RVVFixedLengthData;
8291 return ValidScalableConversion(srcTy, destTy) ||
8292 ValidScalableConversion(destTy, srcTy);
8295 /// Are the two types matrix types and do they have the same dimensions i.e.
8296 /// do they have the same number of rows and the same number of columns?
8297 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
8298 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
8299 return false;
8301 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
8302 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
8304 return matSrcType->getNumRows() == matDestType->getNumRows() &&
8305 matSrcType->getNumColumns() == matDestType->getNumColumns();
8308 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
8309 assert(DestTy->isVectorType() || SrcTy->isVectorType());
8311 uint64_t SrcLen, DestLen;
8312 QualType SrcEltTy, DestEltTy;
8313 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
8314 return false;
8315 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
8316 return false;
8318 // ASTContext::getTypeSize will return the size rounded up to a
8319 // power of 2, so instead of using that, we need to use the raw
8320 // element size multiplied by the element count.
8321 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
8322 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
8324 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
8327 // This returns true if at least one of the types is an altivec vector.
8328 bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {
8329 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
8330 "expected at least one type to be a vector here");
8332 bool IsSrcTyAltivec =
8333 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
8334 VectorKind::AltiVecVector) ||
8335 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8336 VectorKind::AltiVecBool) ||
8337 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8338 VectorKind::AltiVecPixel));
8340 bool IsDestTyAltivec = DestTy->isVectorType() &&
8341 ((DestTy->castAs<VectorType>()->getVectorKind() ==
8342 VectorKind::AltiVecVector) ||
8343 (DestTy->castAs<VectorType>()->getVectorKind() ==
8344 VectorKind::AltiVecBool) ||
8345 (DestTy->castAs<VectorType>()->getVectorKind() ==
8346 VectorKind::AltiVecPixel));
8348 return (IsSrcTyAltivec || IsDestTyAltivec);
8351 /// Are the two types lax-compatible vector types? That is, given
8352 /// that one of them is a vector, do they have equal storage sizes,
8353 /// where the storage size is the number of elements times the element
8354 /// size?
8356 /// This will also return false if either of the types is neither a
8357 /// vector nor a real type.
8358 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
8359 assert(destTy->isVectorType() || srcTy->isVectorType());
8361 // Disallow lax conversions between scalars and ExtVectors (these
8362 // conversions are allowed for other vector types because common headers
8363 // depend on them). Most scalar OP ExtVector cases are handled by the
8364 // splat path anyway, which does what we want (convert, not bitcast).
8365 // What this rules out for ExtVectors is crazy things like char4*float.
8366 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
8367 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
8369 return areVectorTypesSameSize(srcTy, destTy);
8372 /// Is this a legal conversion between two types, one of which is
8373 /// known to be a vector type?
8374 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
8375 assert(destTy->isVectorType() || srcTy->isVectorType());
8377 switch (Context.getLangOpts().getLaxVectorConversions()) {
8378 case LangOptions::LaxVectorConversionKind::None:
8379 return false;
8381 case LangOptions::LaxVectorConversionKind::Integer:
8382 if (!srcTy->isIntegralOrEnumerationType()) {
8383 auto *Vec = srcTy->getAs<VectorType>();
8384 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8385 return false;
8387 if (!destTy->isIntegralOrEnumerationType()) {
8388 auto *Vec = destTy->getAs<VectorType>();
8389 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8390 return false;
8392 // OK, integer (vector) -> integer (vector) bitcast.
8393 break;
8395 case LangOptions::LaxVectorConversionKind::All:
8396 break;
8399 return areLaxCompatibleVectorTypes(srcTy, destTy);
8402 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
8403 CastKind &Kind) {
8404 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
8405 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
8406 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
8407 << DestTy << SrcTy << R;
8409 } else if (SrcTy->isMatrixType()) {
8410 return Diag(R.getBegin(),
8411 diag::err_invalid_conversion_between_matrix_and_type)
8412 << SrcTy << DestTy << R;
8413 } else if (DestTy->isMatrixType()) {
8414 return Diag(R.getBegin(),
8415 diag::err_invalid_conversion_between_matrix_and_type)
8416 << DestTy << SrcTy << R;
8419 Kind = CK_MatrixCast;
8420 return false;
8423 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
8424 CastKind &Kind) {
8425 assert(VectorTy->isVectorType() && "Not a vector type!");
8427 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
8428 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
8429 return Diag(R.getBegin(),
8430 Ty->isVectorType() ?
8431 diag::err_invalid_conversion_between_vectors :
8432 diag::err_invalid_conversion_between_vector_and_integer)
8433 << VectorTy << Ty << R;
8434 } else
8435 return Diag(R.getBegin(),
8436 diag::err_invalid_conversion_between_vector_and_scalar)
8437 << VectorTy << Ty << R;
8439 Kind = CK_BitCast;
8440 return false;
8443 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
8444 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
8446 if (DestElemTy == SplattedExpr->getType())
8447 return SplattedExpr;
8449 assert(DestElemTy->isFloatingType() ||
8450 DestElemTy->isIntegralOrEnumerationType());
8452 CastKind CK;
8453 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
8454 // OpenCL requires that we convert `true` boolean expressions to -1, but
8455 // only when splatting vectors.
8456 if (DestElemTy->isFloatingType()) {
8457 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8458 // in two steps: boolean to signed integral, then to floating.
8459 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
8460 CK_BooleanToSignedIntegral);
8461 SplattedExpr = CastExprRes.get();
8462 CK = CK_IntegralToFloating;
8463 } else {
8464 CK = CK_BooleanToSignedIntegral;
8466 } else {
8467 ExprResult CastExprRes = SplattedExpr;
8468 CK = PrepareScalarCast(CastExprRes, DestElemTy);
8469 if (CastExprRes.isInvalid())
8470 return ExprError();
8471 SplattedExpr = CastExprRes.get();
8473 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
8476 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
8477 Expr *CastExpr, CastKind &Kind) {
8478 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
8480 QualType SrcTy = CastExpr->getType();
8482 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8483 // an ExtVectorType.
8484 // In OpenCL, casts between vectors of different types are not allowed.
8485 // (See OpenCL 6.2).
8486 if (SrcTy->isVectorType()) {
8487 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
8488 (getLangOpts().OpenCL &&
8489 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
8490 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
8491 << DestTy << SrcTy << R;
8492 return ExprError();
8494 Kind = CK_BitCast;
8495 return CastExpr;
8498 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8499 // conversion will take place first from scalar to elt type, and then
8500 // splat from elt type to vector.
8501 if (SrcTy->isPointerType())
8502 return Diag(R.getBegin(),
8503 diag::err_invalid_conversion_between_vector_and_scalar)
8504 << DestTy << SrcTy << R;
8506 Kind = CK_VectorSplat;
8507 return prepareVectorSplat(DestTy, CastExpr);
8510 ExprResult
8511 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
8512 Declarator &D, ParsedType &Ty,
8513 SourceLocation RParenLoc, Expr *CastExpr) {
8514 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
8515 "ActOnCastExpr(): missing type or expr");
8517 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
8518 if (D.isInvalidType())
8519 return ExprError();
8521 if (getLangOpts().CPlusPlus) {
8522 // Check that there are no default arguments (C++ only).
8523 CheckExtraCXXDefaultArguments(D);
8524 } else {
8525 // Make sure any TypoExprs have been dealt with.
8526 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
8527 if (!Res.isUsable())
8528 return ExprError();
8529 CastExpr = Res.get();
8532 checkUnusedDeclAttributes(D);
8534 QualType castType = castTInfo->getType();
8535 Ty = CreateParsedType(castType, castTInfo);
8537 bool isVectorLiteral = false;
8539 // Check for an altivec or OpenCL literal,
8540 // i.e. all the elements are integer constants.
8541 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
8542 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
8543 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8544 && castType->isVectorType() && (PE || PLE)) {
8545 if (PLE && PLE->getNumExprs() == 0) {
8546 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
8547 return ExprError();
8549 if (PE || PLE->getNumExprs() == 1) {
8550 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
8551 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8552 isVectorLiteral = true;
8554 else
8555 isVectorLiteral = true;
8558 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8559 // then handle it as such.
8560 if (isVectorLiteral)
8561 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
8563 // If the Expr being casted is a ParenListExpr, handle it specially.
8564 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8565 // sequence of BinOp comma operators.
8566 if (isa<ParenListExpr>(CastExpr)) {
8567 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
8568 if (Result.isInvalid()) return ExprError();
8569 CastExpr = Result.get();
8572 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8573 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
8575 CheckTollFreeBridgeCast(castType, CastExpr);
8577 CheckObjCBridgeRelatedCast(castType, CastExpr);
8579 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
8581 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
8584 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
8585 SourceLocation RParenLoc, Expr *E,
8586 TypeSourceInfo *TInfo) {
8587 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8588 "Expected paren or paren list expression");
8590 Expr **exprs;
8591 unsigned numExprs;
8592 Expr *subExpr;
8593 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8594 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
8595 LiteralLParenLoc = PE->getLParenLoc();
8596 LiteralRParenLoc = PE->getRParenLoc();
8597 exprs = PE->getExprs();
8598 numExprs = PE->getNumExprs();
8599 } else { // isa<ParenExpr> by assertion at function entrance
8600 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
8601 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
8602 subExpr = cast<ParenExpr>(E)->getSubExpr();
8603 exprs = &subExpr;
8604 numExprs = 1;
8607 QualType Ty = TInfo->getType();
8608 assert(Ty->isVectorType() && "Expected vector type");
8610 SmallVector<Expr *, 8> initExprs;
8611 const VectorType *VTy = Ty->castAs<VectorType>();
8612 unsigned numElems = VTy->getNumElements();
8614 // '(...)' form of vector initialization in AltiVec: the number of
8615 // initializers must be one or must match the size of the vector.
8616 // If a single value is specified in the initializer then it will be
8617 // replicated to all the components of the vector
8618 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
8619 VTy->getElementType()))
8620 return ExprError();
8621 if (ShouldSplatAltivecScalarInCast(VTy)) {
8622 // The number of initializers must be one or must match the size of the
8623 // vector. If a single value is specified in the initializer then it will
8624 // be replicated to all the components of the vector
8625 if (numExprs == 1) {
8626 QualType ElemTy = VTy->getElementType();
8627 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8628 if (Literal.isInvalid())
8629 return ExprError();
8630 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8631 PrepareScalarCast(Literal, ElemTy));
8632 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8634 else if (numExprs < numElems) {
8635 Diag(E->getExprLoc(),
8636 diag::err_incorrect_number_of_vector_initializers);
8637 return ExprError();
8639 else
8640 initExprs.append(exprs, exprs + numExprs);
8642 else {
8643 // For OpenCL, when the number of initializers is a single value,
8644 // it will be replicated to all components of the vector.
8645 if (getLangOpts().OpenCL && VTy->getVectorKind() == VectorKind::Generic &&
8646 numExprs == 1) {
8647 QualType ElemTy = VTy->getElementType();
8648 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8649 if (Literal.isInvalid())
8650 return ExprError();
8651 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8652 PrepareScalarCast(Literal, ElemTy));
8653 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8656 initExprs.append(exprs, exprs + numExprs);
8658 // FIXME: This means that pretty-printing the final AST will produce curly
8659 // braces instead of the original commas.
8660 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8661 initExprs, LiteralRParenLoc);
8662 initE->setType(Ty);
8663 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8666 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
8667 /// the ParenListExpr into a sequence of comma binary operators.
8668 ExprResult
8669 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8670 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8671 if (!E)
8672 return OrigExpr;
8674 ExprResult Result(E->getExpr(0));
8676 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8677 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8678 E->getExpr(i));
8680 if (Result.isInvalid()) return ExprError();
8682 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8685 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8686 SourceLocation R,
8687 MultiExprArg Val) {
8688 return ParenListExpr::Create(Context, L, Val, R);
8691 /// Emit a specialized diagnostic when one expression is a null pointer
8692 /// constant and the other is not a pointer. Returns true if a diagnostic is
8693 /// emitted.
8694 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
8695 SourceLocation QuestionLoc) {
8696 Expr *NullExpr = LHSExpr;
8697 Expr *NonPointerExpr = RHSExpr;
8698 Expr::NullPointerConstantKind NullKind =
8699 NullExpr->isNullPointerConstant(Context,
8700 Expr::NPC_ValueDependentIsNotNull);
8702 if (NullKind == Expr::NPCK_NotNull) {
8703 NullExpr = RHSExpr;
8704 NonPointerExpr = LHSExpr;
8705 NullKind =
8706 NullExpr->isNullPointerConstant(Context,
8707 Expr::NPC_ValueDependentIsNotNull);
8710 if (NullKind == Expr::NPCK_NotNull)
8711 return false;
8713 if (NullKind == Expr::NPCK_ZeroExpression)
8714 return false;
8716 if (NullKind == Expr::NPCK_ZeroLiteral) {
8717 // In this case, check to make sure that we got here from a "NULL"
8718 // string in the source code.
8719 NullExpr = NullExpr->IgnoreParenImpCasts();
8720 SourceLocation loc = NullExpr->getExprLoc();
8721 if (!findMacroSpelling(loc, "NULL"))
8722 return false;
8725 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8726 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8727 << NonPointerExpr->getType() << DiagType
8728 << NonPointerExpr->getSourceRange();
8729 return true;
8732 /// Return false if the condition expression is valid, true otherwise.
8733 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
8734 QualType CondTy = Cond->getType();
8736 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8737 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8738 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8739 << CondTy << Cond->getSourceRange();
8740 return true;
8743 // C99 6.5.15p2
8744 if (CondTy->isScalarType()) return false;
8746 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8747 << CondTy << Cond->getSourceRange();
8748 return true;
8751 /// Return false if the NullExpr can be promoted to PointerTy,
8752 /// true otherwise.
8753 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8754 QualType PointerTy) {
8755 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8756 !NullExpr.get()->isNullPointerConstant(S.Context,
8757 Expr::NPC_ValueDependentIsNull))
8758 return true;
8760 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8761 return false;
8764 /// Checks compatibility between two pointers and return the resulting
8765 /// type.
8766 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8767 ExprResult &RHS,
8768 SourceLocation Loc) {
8769 QualType LHSTy = LHS.get()->getType();
8770 QualType RHSTy = RHS.get()->getType();
8772 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8773 // Two identical pointers types are always compatible.
8774 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8777 QualType lhptee, rhptee;
8779 // Get the pointee types.
8780 bool IsBlockPointer = false;
8781 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8782 lhptee = LHSBTy->getPointeeType();
8783 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8784 IsBlockPointer = true;
8785 } else {
8786 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8787 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8790 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8791 // differently qualified versions of compatible types, the result type is
8792 // a pointer to an appropriately qualified version of the composite
8793 // type.
8795 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8796 // clause doesn't make sense for our extensions. E.g. address space 2 should
8797 // be incompatible with address space 3: they may live on different devices or
8798 // anything.
8799 Qualifiers lhQual = lhptee.getQualifiers();
8800 Qualifiers rhQual = rhptee.getQualifiers();
8802 LangAS ResultAddrSpace = LangAS::Default;
8803 LangAS LAddrSpace = lhQual.getAddressSpace();
8804 LangAS RAddrSpace = rhQual.getAddressSpace();
8806 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8807 // spaces is disallowed.
8808 if (lhQual.isAddressSpaceSupersetOf(rhQual))
8809 ResultAddrSpace = LAddrSpace;
8810 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
8811 ResultAddrSpace = RAddrSpace;
8812 else {
8813 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8814 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8815 << RHS.get()->getSourceRange();
8816 return QualType();
8819 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8820 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8821 lhQual.removeCVRQualifiers();
8822 rhQual.removeCVRQualifiers();
8824 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8825 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8826 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8827 // qual types are compatible iff
8828 // * corresponded types are compatible
8829 // * CVR qualifiers are equal
8830 // * address spaces are equal
8831 // Thus for conditional operator we merge CVR and address space unqualified
8832 // pointees and if there is a composite type we return a pointer to it with
8833 // merged qualifiers.
8834 LHSCastKind =
8835 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8836 RHSCastKind =
8837 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8838 lhQual.removeAddressSpace();
8839 rhQual.removeAddressSpace();
8841 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8842 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8844 QualType CompositeTy = S.Context.mergeTypes(
8845 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8846 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8848 if (CompositeTy.isNull()) {
8849 // In this situation, we assume void* type. No especially good
8850 // reason, but this is what gcc does, and we do have to pick
8851 // to get a consistent AST.
8852 QualType incompatTy;
8853 incompatTy = S.Context.getPointerType(
8854 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8855 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8856 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8858 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8859 // for casts between types with incompatible address space qualifiers.
8860 // For the following code the compiler produces casts between global and
8861 // local address spaces of the corresponded innermost pointees:
8862 // local int *global *a;
8863 // global int *global *b;
8864 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8865 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8866 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8867 << RHS.get()->getSourceRange();
8869 return incompatTy;
8872 // The pointer types are compatible.
8873 // In case of OpenCL ResultTy should have the address space qualifier
8874 // which is a superset of address spaces of both the 2nd and the 3rd
8875 // operands of the conditional operator.
8876 QualType ResultTy = [&, ResultAddrSpace]() {
8877 if (S.getLangOpts().OpenCL) {
8878 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8879 CompositeQuals.setAddressSpace(ResultAddrSpace);
8880 return S.Context
8881 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8882 .withCVRQualifiers(MergedCVRQual);
8884 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8885 }();
8886 if (IsBlockPointer)
8887 ResultTy = S.Context.getBlockPointerType(ResultTy);
8888 else
8889 ResultTy = S.Context.getPointerType(ResultTy);
8891 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8892 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8893 return ResultTy;
8896 /// Return the resulting type when the operands are both block pointers.
8897 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8898 ExprResult &LHS,
8899 ExprResult &RHS,
8900 SourceLocation Loc) {
8901 QualType LHSTy = LHS.get()->getType();
8902 QualType RHSTy = RHS.get()->getType();
8904 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8905 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8906 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8907 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8908 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8909 return destType;
8911 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8912 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8913 << RHS.get()->getSourceRange();
8914 return QualType();
8917 // We have 2 block pointer types.
8918 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8921 /// Return the resulting type when the operands are both pointers.
8922 static QualType
8923 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8924 ExprResult &RHS,
8925 SourceLocation Loc) {
8926 // get the pointer types
8927 QualType LHSTy = LHS.get()->getType();
8928 QualType RHSTy = RHS.get()->getType();
8930 // get the "pointed to" types
8931 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8932 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8934 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8935 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8936 // Figure out necessary qualifiers (C99 6.5.15p6)
8937 QualType destPointee
8938 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8939 QualType destType = S.Context.getPointerType(destPointee);
8940 // Add qualifiers if necessary.
8941 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8942 // Promote to void*.
8943 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8944 return destType;
8946 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8947 QualType destPointee
8948 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8949 QualType destType = S.Context.getPointerType(destPointee);
8950 // Add qualifiers if necessary.
8951 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8952 // Promote to void*.
8953 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8954 return destType;
8957 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8960 /// Return false if the first expression is not an integer and the second
8961 /// expression is not a pointer, true otherwise.
8962 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8963 Expr* PointerExpr, SourceLocation Loc,
8964 bool IsIntFirstExpr) {
8965 if (!PointerExpr->getType()->isPointerType() ||
8966 !Int.get()->getType()->isIntegerType())
8967 return false;
8969 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8970 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8972 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8973 << Expr1->getType() << Expr2->getType()
8974 << Expr1->getSourceRange() << Expr2->getSourceRange();
8975 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8976 CK_IntegralToPointer);
8977 return true;
8980 /// Simple conversion between integer and floating point types.
8982 /// Used when handling the OpenCL conditional operator where the
8983 /// condition is a vector while the other operands are scalar.
8985 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8986 /// types are either integer or floating type. Between the two
8987 /// operands, the type with the higher rank is defined as the "result
8988 /// type". The other operand needs to be promoted to the same type. No
8989 /// other type promotion is allowed. We cannot use
8990 /// UsualArithmeticConversions() for this purpose, since it always
8991 /// promotes promotable types.
8992 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8993 ExprResult &RHS,
8994 SourceLocation QuestionLoc) {
8995 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8996 if (LHS.isInvalid())
8997 return QualType();
8998 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8999 if (RHS.isInvalid())
9000 return QualType();
9002 // For conversion purposes, we ignore any qualifiers.
9003 // For example, "const float" and "float" are equivalent.
9004 QualType LHSType =
9005 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
9006 QualType RHSType =
9007 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
9009 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
9010 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
9011 << LHSType << LHS.get()->getSourceRange();
9012 return QualType();
9015 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
9016 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
9017 << RHSType << RHS.get()->getSourceRange();
9018 return QualType();
9021 // If both types are identical, no conversion is needed.
9022 if (LHSType == RHSType)
9023 return LHSType;
9025 // Now handle "real" floating types (i.e. float, double, long double).
9026 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
9027 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
9028 /*IsCompAssign = */ false);
9030 // Finally, we have two differing integer types.
9031 return handleIntegerConversion<doIntegralCast, doIntegralCast>
9032 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
9035 /// Convert scalar operands to a vector that matches the
9036 /// condition in length.
9038 /// Used when handling the OpenCL conditional operator where the
9039 /// condition is a vector while the other operands are scalar.
9041 /// We first compute the "result type" for the scalar operands
9042 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
9043 /// into a vector of that type where the length matches the condition
9044 /// vector type. s6.11.6 requires that the element types of the result
9045 /// and the condition must have the same number of bits.
9046 static QualType
9047 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
9048 QualType CondTy, SourceLocation QuestionLoc) {
9049 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
9050 if (ResTy.isNull()) return QualType();
9052 const VectorType *CV = CondTy->getAs<VectorType>();
9053 assert(CV);
9055 // Determine the vector result type
9056 unsigned NumElements = CV->getNumElements();
9057 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
9059 // Ensure that all types have the same number of bits
9060 if (S.Context.getTypeSize(CV->getElementType())
9061 != S.Context.getTypeSize(ResTy)) {
9062 // Since VectorTy is created internally, it does not pretty print
9063 // with an OpenCL name. Instead, we just print a description.
9064 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
9065 SmallString<64> Str;
9066 llvm::raw_svector_ostream OS(Str);
9067 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
9068 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
9069 << CondTy << OS.str();
9070 return QualType();
9073 // Convert operands to the vector result type
9074 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
9075 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
9077 return VectorTy;
9080 /// Return false if this is a valid OpenCL condition vector
9081 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
9082 SourceLocation QuestionLoc) {
9083 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
9084 // integral type.
9085 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
9086 assert(CondTy);
9087 QualType EleTy = CondTy->getElementType();
9088 if (EleTy->isIntegerType()) return false;
9090 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
9091 << Cond->getType() << Cond->getSourceRange();
9092 return true;
9095 /// Return false if the vector condition type and the vector
9096 /// result type are compatible.
9098 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
9099 /// number of elements, and their element types have the same number
9100 /// of bits.
9101 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
9102 SourceLocation QuestionLoc) {
9103 const VectorType *CV = CondTy->getAs<VectorType>();
9104 const VectorType *RV = VecResTy->getAs<VectorType>();
9105 assert(CV && RV);
9107 if (CV->getNumElements() != RV->getNumElements()) {
9108 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
9109 << CondTy << VecResTy;
9110 return true;
9113 QualType CVE = CV->getElementType();
9114 QualType RVE = RV->getElementType();
9116 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
9117 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
9118 << CondTy << VecResTy;
9119 return true;
9122 return false;
9125 /// Return the resulting type for the conditional operator in
9126 /// OpenCL (aka "ternary selection operator", OpenCL v1.1
9127 /// s6.3.i) when the condition is a vector type.
9128 static QualType
9129 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
9130 ExprResult &LHS, ExprResult &RHS,
9131 SourceLocation QuestionLoc) {
9132 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
9133 if (Cond.isInvalid())
9134 return QualType();
9135 QualType CondTy = Cond.get()->getType();
9137 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
9138 return QualType();
9140 // If either operand is a vector then find the vector type of the
9141 // result as specified in OpenCL v1.1 s6.3.i.
9142 if (LHS.get()->getType()->isVectorType() ||
9143 RHS.get()->getType()->isVectorType()) {
9144 bool IsBoolVecLang =
9145 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
9146 QualType VecResTy =
9147 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
9148 /*isCompAssign*/ false,
9149 /*AllowBothBool*/ true,
9150 /*AllowBoolConversions*/ false,
9151 /*AllowBooleanOperation*/ IsBoolVecLang,
9152 /*ReportInvalid*/ true);
9153 if (VecResTy.isNull())
9154 return QualType();
9155 // The result type must match the condition type as specified in
9156 // OpenCL v1.1 s6.11.6.
9157 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
9158 return QualType();
9159 return VecResTy;
9162 // Both operands are scalar.
9163 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
9166 /// Return true if the Expr is block type
9167 static bool checkBlockType(Sema &S, const Expr *E) {
9168 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9169 QualType Ty = CE->getCallee()->getType();
9170 if (Ty->isBlockPointerType()) {
9171 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
9172 return true;
9175 return false;
9178 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
9179 /// In that case, LHS = cond.
9180 /// C99 6.5.15
9181 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
9182 ExprResult &RHS, ExprValueKind &VK,
9183 ExprObjectKind &OK,
9184 SourceLocation QuestionLoc) {
9186 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
9187 if (!LHSResult.isUsable()) return QualType();
9188 LHS = LHSResult;
9190 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
9191 if (!RHSResult.isUsable()) return QualType();
9192 RHS = RHSResult;
9194 // C++ is sufficiently different to merit its own checker.
9195 if (getLangOpts().CPlusPlus)
9196 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
9198 VK = VK_PRValue;
9199 OK = OK_Ordinary;
9201 if (Context.isDependenceAllowed() &&
9202 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
9203 RHS.get()->isTypeDependent())) {
9204 assert(!getLangOpts().CPlusPlus);
9205 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
9206 RHS.get()->containsErrors()) &&
9207 "should only occur in error-recovery path.");
9208 return Context.DependentTy;
9211 // The OpenCL operator with a vector condition is sufficiently
9212 // different to merit its own checker.
9213 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
9214 Cond.get()->getType()->isExtVectorType())
9215 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
9217 // First, check the condition.
9218 Cond = UsualUnaryConversions(Cond.get());
9219 if (Cond.isInvalid())
9220 return QualType();
9221 if (checkCondition(*this, Cond.get(), QuestionLoc))
9222 return QualType();
9224 // Handle vectors.
9225 if (LHS.get()->getType()->isVectorType() ||
9226 RHS.get()->getType()->isVectorType())
9227 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
9228 /*AllowBothBool*/ true,
9229 /*AllowBoolConversions*/ false,
9230 /*AllowBooleanOperation*/ false,
9231 /*ReportInvalid*/ true);
9233 QualType ResTy =
9234 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
9235 if (LHS.isInvalid() || RHS.isInvalid())
9236 return QualType();
9238 // WebAssembly tables are not allowed as conditional LHS or RHS.
9239 QualType LHSTy = LHS.get()->getType();
9240 QualType RHSTy = RHS.get()->getType();
9241 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
9242 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
9243 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9244 return QualType();
9247 // Diagnose attempts to convert between __ibm128, __float128 and long double
9248 // where such conversions currently can't be handled.
9249 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
9250 Diag(QuestionLoc,
9251 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
9252 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9253 return QualType();
9256 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
9257 // selection operator (?:).
9258 if (getLangOpts().OpenCL &&
9259 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
9260 return QualType();
9263 // If both operands have arithmetic type, do the usual arithmetic conversions
9264 // to find a common type: C99 6.5.15p3,5.
9265 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
9266 // Disallow invalid arithmetic conversions, such as those between bit-
9267 // precise integers types of different sizes, or between a bit-precise
9268 // integer and another type.
9269 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
9270 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
9271 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9272 << RHS.get()->getSourceRange();
9273 return QualType();
9276 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
9277 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
9279 return ResTy;
9282 // If both operands are the same structure or union type, the result is that
9283 // type.
9284 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
9285 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
9286 if (LHSRT->getDecl() == RHSRT->getDecl())
9287 // "If both the operands have structure or union type, the result has
9288 // that type." This implies that CV qualifiers are dropped.
9289 return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(),
9290 RHSTy.getUnqualifiedType());
9291 // FIXME: Type of conditional expression must be complete in C mode.
9294 // C99 6.5.15p5: "If both operands have void type, the result has void type."
9295 // The following || allows only one side to be void (a GCC-ism).
9296 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
9297 QualType ResTy;
9298 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
9299 ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
9300 } else if (RHSTy->isVoidType()) {
9301 ResTy = RHSTy;
9302 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
9303 << RHS.get()->getSourceRange();
9304 } else {
9305 ResTy = LHSTy;
9306 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
9307 << LHS.get()->getSourceRange();
9309 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
9310 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
9311 return ResTy;
9314 // C23 6.5.15p7:
9315 // ... if both the second and third operands have nullptr_t type, the
9316 // result also has that type.
9317 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
9318 return ResTy;
9320 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
9321 // the type of the other operand."
9322 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
9323 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
9325 // All objective-c pointer type analysis is done here.
9326 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
9327 QuestionLoc);
9328 if (LHS.isInvalid() || RHS.isInvalid())
9329 return QualType();
9330 if (!compositeType.isNull())
9331 return compositeType;
9334 // Handle block pointer types.
9335 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
9336 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
9337 QuestionLoc);
9339 // Check constraints for C object pointers types (C99 6.5.15p3,6).
9340 if (LHSTy->isPointerType() && RHSTy->isPointerType())
9341 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
9342 QuestionLoc);
9344 // GCC compatibility: soften pointer/integer mismatch. Note that
9345 // null pointers have been filtered out by this point.
9346 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
9347 /*IsIntFirstExpr=*/true))
9348 return RHSTy;
9349 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
9350 /*IsIntFirstExpr=*/false))
9351 return LHSTy;
9353 // Emit a better diagnostic if one of the expressions is a null pointer
9354 // constant and the other is not a pointer type. In this case, the user most
9355 // likely forgot to take the address of the other expression.
9356 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
9357 return QualType();
9359 // Finally, if the LHS and RHS types are canonically the same type, we can
9360 // use the common sugared type.
9361 if (Context.hasSameType(LHSTy, RHSTy))
9362 return Context.getCommonSugaredType(LHSTy, RHSTy);
9364 // Otherwise, the operands are not compatible.
9365 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
9366 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9367 << RHS.get()->getSourceRange();
9368 return QualType();
9371 /// FindCompositeObjCPointerType - Helper method to find composite type of
9372 /// two objective-c pointer types of the two input expressions.
9373 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
9374 SourceLocation QuestionLoc) {
9375 QualType LHSTy = LHS.get()->getType();
9376 QualType RHSTy = RHS.get()->getType();
9378 // Handle things like Class and struct objc_class*. Here we case the result
9379 // to the pseudo-builtin, because that will be implicitly cast back to the
9380 // redefinition type if an attempt is made to access its fields.
9381 if (LHSTy->isObjCClassType() &&
9382 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
9383 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
9384 return LHSTy;
9386 if (RHSTy->isObjCClassType() &&
9387 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
9388 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
9389 return RHSTy;
9391 // And the same for struct objc_object* / id
9392 if (LHSTy->isObjCIdType() &&
9393 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
9394 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
9395 return LHSTy;
9397 if (RHSTy->isObjCIdType() &&
9398 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
9399 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
9400 return RHSTy;
9402 // And the same for struct objc_selector* / SEL
9403 if (Context.isObjCSelType(LHSTy) &&
9404 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
9405 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
9406 return LHSTy;
9408 if (Context.isObjCSelType(RHSTy) &&
9409 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
9410 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
9411 return RHSTy;
9413 // Check constraints for Objective-C object pointers types.
9414 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
9416 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
9417 // Two identical object pointer types are always compatible.
9418 return LHSTy;
9420 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
9421 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
9422 QualType compositeType = LHSTy;
9424 // If both operands are interfaces and either operand can be
9425 // assigned to the other, use that type as the composite
9426 // type. This allows
9427 // xxx ? (A*) a : (B*) b
9428 // where B is a subclass of A.
9430 // Additionally, as for assignment, if either type is 'id'
9431 // allow silent coercion. Finally, if the types are
9432 // incompatible then make sure to use 'id' as the composite
9433 // type so the result is acceptable for sending messages to.
9435 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
9436 // It could return the composite type.
9437 if (!(compositeType =
9438 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
9439 // Nothing more to do.
9440 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
9441 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
9442 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
9443 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
9444 } else if ((LHSOPT->isObjCQualifiedIdType() ||
9445 RHSOPT->isObjCQualifiedIdType()) &&
9446 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
9447 true)) {
9448 // Need to handle "id<xx>" explicitly.
9449 // GCC allows qualified id and any Objective-C type to devolve to
9450 // id. Currently localizing to here until clear this should be
9451 // part of ObjCQualifiedIdTypesAreCompatible.
9452 compositeType = Context.getObjCIdType();
9453 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
9454 compositeType = Context.getObjCIdType();
9455 } else {
9456 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
9457 << LHSTy << RHSTy
9458 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9459 QualType incompatTy = Context.getObjCIdType();
9460 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
9461 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
9462 return incompatTy;
9464 // The object pointer types are compatible.
9465 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
9466 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
9467 return compositeType;
9469 // Check Objective-C object pointer types and 'void *'
9470 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
9471 if (getLangOpts().ObjCAutoRefCount) {
9472 // ARC forbids the implicit conversion of object pointers to 'void *',
9473 // so these types are not compatible.
9474 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
9475 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9476 LHS = RHS = true;
9477 return QualType();
9479 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
9480 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
9481 QualType destPointee
9482 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
9483 QualType destType = Context.getPointerType(destPointee);
9484 // Add qualifiers if necessary.
9485 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
9486 // Promote to void*.
9487 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
9488 return destType;
9490 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
9491 if (getLangOpts().ObjCAutoRefCount) {
9492 // ARC forbids the implicit conversion of object pointers to 'void *',
9493 // so these types are not compatible.
9494 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
9495 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9496 LHS = RHS = true;
9497 return QualType();
9499 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
9500 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
9501 QualType destPointee
9502 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
9503 QualType destType = Context.getPointerType(destPointee);
9504 // Add qualifiers if necessary.
9505 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
9506 // Promote to void*.
9507 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
9508 return destType;
9510 return QualType();
9513 /// SuggestParentheses - Emit a note with a fixit hint that wraps
9514 /// ParenRange in parentheses.
9515 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
9516 const PartialDiagnostic &Note,
9517 SourceRange ParenRange) {
9518 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
9519 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
9520 EndLoc.isValid()) {
9521 Self.Diag(Loc, Note)
9522 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
9523 << FixItHint::CreateInsertion(EndLoc, ")");
9524 } else {
9525 // We can't display the parentheses, so just show the bare note.
9526 Self.Diag(Loc, Note) << ParenRange;
9530 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
9531 return BinaryOperator::isAdditiveOp(Opc) ||
9532 BinaryOperator::isMultiplicativeOp(Opc) ||
9533 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
9534 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9535 // not any of the logical operators. Bitwise-xor is commonly used as a
9536 // logical-xor because there is no logical-xor operator. The logical
9537 // operators, including uses of xor, have a high false positive rate for
9538 // precedence warnings.
9541 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9542 /// expression, either using a built-in or overloaded operator,
9543 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9544 /// expression.
9545 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
9546 Expr **RHSExprs) {
9547 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9548 E = E->IgnoreImpCasts();
9549 E = E->IgnoreConversionOperatorSingleStep();
9550 E = E->IgnoreImpCasts();
9551 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
9552 E = MTE->getSubExpr();
9553 E = E->IgnoreImpCasts();
9556 // Built-in binary operator.
9557 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
9558 if (IsArithmeticOp(OP->getOpcode())) {
9559 *Opcode = OP->getOpcode();
9560 *RHSExprs = OP->getRHS();
9561 return true;
9565 // Overloaded operator.
9566 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
9567 if (Call->getNumArgs() != 2)
9568 return false;
9570 // Make sure this is really a binary operator that is safe to pass into
9571 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9572 OverloadedOperatorKind OO = Call->getOperator();
9573 if (OO < OO_Plus || OO > OO_Arrow ||
9574 OO == OO_PlusPlus || OO == OO_MinusMinus)
9575 return false;
9577 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
9578 if (IsArithmeticOp(OpKind)) {
9579 *Opcode = OpKind;
9580 *RHSExprs = Call->getArg(1);
9581 return true;
9585 return false;
9588 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9589 /// or is a logical expression such as (x==y) which has int type, but is
9590 /// commonly interpreted as boolean.
9591 static bool ExprLooksBoolean(Expr *E) {
9592 E = E->IgnoreParenImpCasts();
9594 if (E->getType()->isBooleanType())
9595 return true;
9596 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
9597 return OP->isComparisonOp() || OP->isLogicalOp();
9598 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
9599 return OP->getOpcode() == UO_LNot;
9600 if (E->getType()->isPointerType())
9601 return true;
9602 // FIXME: What about overloaded operator calls returning "unspecified boolean
9603 // type"s (commonly pointer-to-members)?
9605 return false;
9608 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9609 /// and binary operator are mixed in a way that suggests the programmer assumed
9610 /// the conditional operator has higher precedence, for example:
9611 /// "int x = a + someBinaryCondition ? 1 : 2".
9612 static void DiagnoseConditionalPrecedence(Sema &Self,
9613 SourceLocation OpLoc,
9614 Expr *Condition,
9615 Expr *LHSExpr,
9616 Expr *RHSExpr) {
9617 BinaryOperatorKind CondOpcode;
9618 Expr *CondRHS;
9620 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
9621 return;
9622 if (!ExprLooksBoolean(CondRHS))
9623 return;
9625 // The condition is an arithmetic binary expression, with a right-
9626 // hand side that looks boolean, so warn.
9628 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
9629 ? diag::warn_precedence_bitwise_conditional
9630 : diag::warn_precedence_conditional;
9632 Self.Diag(OpLoc, DiagID)
9633 << Condition->getSourceRange()
9634 << BinaryOperator::getOpcodeStr(CondOpcode);
9636 SuggestParentheses(
9637 Self, OpLoc,
9638 Self.PDiag(diag::note_precedence_silence)
9639 << BinaryOperator::getOpcodeStr(CondOpcode),
9640 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9642 SuggestParentheses(Self, OpLoc,
9643 Self.PDiag(diag::note_precedence_conditional_first),
9644 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9647 /// Compute the nullability of a conditional expression.
9648 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
9649 QualType LHSTy, QualType RHSTy,
9650 ASTContext &Ctx) {
9651 if (!ResTy->isAnyPointerType())
9652 return ResTy;
9654 auto GetNullability = [](QualType Ty) {
9655 std::optional<NullabilityKind> Kind = Ty->getNullability();
9656 if (Kind) {
9657 // For our purposes, treat _Nullable_result as _Nullable.
9658 if (*Kind == NullabilityKind::NullableResult)
9659 return NullabilityKind::Nullable;
9660 return *Kind;
9662 return NullabilityKind::Unspecified;
9665 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9666 NullabilityKind MergedKind;
9668 // Compute nullability of a binary conditional expression.
9669 if (IsBin) {
9670 if (LHSKind == NullabilityKind::NonNull)
9671 MergedKind = NullabilityKind::NonNull;
9672 else
9673 MergedKind = RHSKind;
9674 // Compute nullability of a normal conditional expression.
9675 } else {
9676 if (LHSKind == NullabilityKind::Nullable ||
9677 RHSKind == NullabilityKind::Nullable)
9678 MergedKind = NullabilityKind::Nullable;
9679 else if (LHSKind == NullabilityKind::NonNull)
9680 MergedKind = RHSKind;
9681 else if (RHSKind == NullabilityKind::NonNull)
9682 MergedKind = LHSKind;
9683 else
9684 MergedKind = NullabilityKind::Unspecified;
9687 // Return if ResTy already has the correct nullability.
9688 if (GetNullability(ResTy) == MergedKind)
9689 return ResTy;
9691 // Strip all nullability from ResTy.
9692 while (ResTy->getNullability())
9693 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9695 // Create a new AttributedType with the new nullability kind.
9696 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
9697 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
9700 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
9701 /// in the case of a the GNU conditional expr extension.
9702 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9703 SourceLocation ColonLoc,
9704 Expr *CondExpr, Expr *LHSExpr,
9705 Expr *RHSExpr) {
9706 if (!Context.isDependenceAllowed()) {
9707 // C cannot handle TypoExpr nodes in the condition because it
9708 // doesn't handle dependent types properly, so make sure any TypoExprs have
9709 // been dealt with before checking the operands.
9710 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
9711 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
9712 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
9714 if (!CondResult.isUsable())
9715 return ExprError();
9717 if (LHSExpr) {
9718 if (!LHSResult.isUsable())
9719 return ExprError();
9722 if (!RHSResult.isUsable())
9723 return ExprError();
9725 CondExpr = CondResult.get();
9726 LHSExpr = LHSResult.get();
9727 RHSExpr = RHSResult.get();
9730 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9731 // was the condition.
9732 OpaqueValueExpr *opaqueValue = nullptr;
9733 Expr *commonExpr = nullptr;
9734 if (!LHSExpr) {
9735 commonExpr = CondExpr;
9736 // Lower out placeholder types first. This is important so that we don't
9737 // try to capture a placeholder. This happens in few cases in C++; such
9738 // as Objective-C++'s dictionary subscripting syntax.
9739 if (commonExpr->hasPlaceholderType()) {
9740 ExprResult result = CheckPlaceholderExpr(commonExpr);
9741 if (!result.isUsable()) return ExprError();
9742 commonExpr = result.get();
9744 // We usually want to apply unary conversions *before* saving, except
9745 // in the special case of a C++ l-value conditional.
9746 if (!(getLangOpts().CPlusPlus
9747 && !commonExpr->isTypeDependent()
9748 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9749 && commonExpr->isGLValue()
9750 && commonExpr->isOrdinaryOrBitFieldObject()
9751 && RHSExpr->isOrdinaryOrBitFieldObject()
9752 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9753 ExprResult commonRes = UsualUnaryConversions(commonExpr);
9754 if (commonRes.isInvalid())
9755 return ExprError();
9756 commonExpr = commonRes.get();
9759 // If the common expression is a class or array prvalue, materialize it
9760 // so that we can safely refer to it multiple times.
9761 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9762 commonExpr->getType()->isArrayType())) {
9763 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9764 if (MatExpr.isInvalid())
9765 return ExprError();
9766 commonExpr = MatExpr.get();
9769 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9770 commonExpr->getType(),
9771 commonExpr->getValueKind(),
9772 commonExpr->getObjectKind(),
9773 commonExpr);
9774 LHSExpr = CondExpr = opaqueValue;
9777 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9778 ExprValueKind VK = VK_PRValue;
9779 ExprObjectKind OK = OK_Ordinary;
9780 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9781 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9782 VK, OK, QuestionLoc);
9783 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9784 RHS.isInvalid())
9785 return ExprError();
9787 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9788 RHS.get());
9790 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9792 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9793 Context);
9795 if (!commonExpr)
9796 return new (Context)
9797 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9798 RHS.get(), result, VK, OK);
9800 return new (Context) BinaryConditionalOperator(
9801 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9802 ColonLoc, result, VK, OK);
9805 // Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible.
9806 bool Sema::IsInvalidSMECallConversion(QualType FromType, QualType ToType,
9807 AArch64SMECallConversionKind C) {
9808 unsigned FromAttributes = 0, ToAttributes = 0;
9809 if (const auto *FromFn =
9810 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
9811 FromAttributes =
9812 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9813 if (const auto *ToFn =
9814 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
9815 ToAttributes =
9816 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9818 if (FromAttributes == ToAttributes)
9819 return false;
9821 // If the '__arm_preserves_za' is the only difference between the types,
9822 // check whether we're allowed to add or remove it.
9823 if ((FromAttributes ^ ToAttributes) ==
9824 FunctionType::SME_PStateZAPreservedMask) {
9825 switch (C) {
9826 case AArch64SMECallConversionKind::MatchExactly:
9827 return true;
9828 case AArch64SMECallConversionKind::MayAddPreservesZA:
9829 return !(ToAttributes & FunctionType::SME_PStateZAPreservedMask);
9830 case AArch64SMECallConversionKind::MayDropPreservesZA:
9831 return !(FromAttributes & FunctionType::SME_PStateZAPreservedMask);
9835 // There has been a mismatch of attributes
9836 return true;
9839 // Check if we have a conversion between incompatible cmse function pointer
9840 // types, that is, a conversion between a function pointer with the
9841 // cmse_nonsecure_call attribute and one without.
9842 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
9843 QualType ToType) {
9844 if (const auto *ToFn =
9845 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
9846 if (const auto *FromFn =
9847 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
9848 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9849 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9851 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9854 return false;
9857 // checkPointerTypesForAssignment - This is a very tricky routine (despite
9858 // being closely modeled after the C99 spec:-). The odd characteristic of this
9859 // routine is it effectively iqnores the qualifiers on the top level pointee.
9860 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9861 // FIXME: add a couple examples in this comment.
9862 static Sema::AssignConvertType
9863 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType,
9864 SourceLocation Loc) {
9865 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9866 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9868 // get the "pointed to" type (ignoring qualifiers at the top level)
9869 const Type *lhptee, *rhptee;
9870 Qualifiers lhq, rhq;
9871 std::tie(lhptee, lhq) =
9872 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9873 std::tie(rhptee, rhq) =
9874 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9876 Sema::AssignConvertType ConvTy = Sema::Compatible;
9878 // C99 6.5.16.1p1: This following citation is common to constraints
9879 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9880 // qualifiers of the type *pointed to* by the right;
9882 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9883 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9884 lhq.compatiblyIncludesObjCLifetime(rhq)) {
9885 // Ignore lifetime for further calculation.
9886 lhq.removeObjCLifetime();
9887 rhq.removeObjCLifetime();
9890 if (!lhq.compatiblyIncludes(rhq)) {
9891 // Treat address-space mismatches as fatal.
9892 if (!lhq.isAddressSpaceSupersetOf(rhq))
9893 return Sema::IncompatiblePointerDiscardsQualifiers;
9895 // It's okay to add or remove GC or lifetime qualifiers when converting to
9896 // and from void*.
9897 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
9898 .compatiblyIncludes(
9899 rhq.withoutObjCGCAttr().withoutObjCLifetime())
9900 && (lhptee->isVoidType() || rhptee->isVoidType()))
9901 ; // keep old
9903 // Treat lifetime mismatches as fatal.
9904 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9905 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
9907 // For GCC/MS compatibility, other qualifier mismatches are treated
9908 // as still compatible in C.
9909 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9912 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9913 // incomplete type and the other is a pointer to a qualified or unqualified
9914 // version of void...
9915 if (lhptee->isVoidType()) {
9916 if (rhptee->isIncompleteOrObjectType())
9917 return ConvTy;
9919 // As an extension, we allow cast to/from void* to function pointer.
9920 assert(rhptee->isFunctionType());
9921 return Sema::FunctionVoidPointer;
9924 if (rhptee->isVoidType()) {
9925 if (lhptee->isIncompleteOrObjectType())
9926 return ConvTy;
9928 // As an extension, we allow cast to/from void* to function pointer.
9929 assert(lhptee->isFunctionType());
9930 return Sema::FunctionVoidPointer;
9933 if (!S.Diags.isIgnored(
9934 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9935 Loc) &&
9936 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9937 !S.IsFunctionConversion(RHSType, LHSType, RHSType))
9938 return Sema::IncompatibleFunctionPointerStrict;
9940 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9941 // unqualified versions of compatible types, ...
9942 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9943 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9944 // Check if the pointee types are compatible ignoring the sign.
9945 // We explicitly check for char so that we catch "char" vs
9946 // "unsigned char" on systems where "char" is unsigned.
9947 if (lhptee->isCharType())
9948 ltrans = S.Context.UnsignedCharTy;
9949 else if (lhptee->hasSignedIntegerRepresentation())
9950 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9952 if (rhptee->isCharType())
9953 rtrans = S.Context.UnsignedCharTy;
9954 else if (rhptee->hasSignedIntegerRepresentation())
9955 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9957 if (ltrans == rtrans) {
9958 // Types are compatible ignoring the sign. Qualifier incompatibility
9959 // takes priority over sign incompatibility because the sign
9960 // warning can be disabled.
9961 if (ConvTy != Sema::Compatible)
9962 return ConvTy;
9964 return Sema::IncompatiblePointerSign;
9967 // If we are a multi-level pointer, it's possible that our issue is simply
9968 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9969 // the eventual target type is the same and the pointers have the same
9970 // level of indirection, this must be the issue.
9971 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9972 do {
9973 std::tie(lhptee, lhq) =
9974 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9975 std::tie(rhptee, rhq) =
9976 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9978 // Inconsistent address spaces at this point is invalid, even if the
9979 // address spaces would be compatible.
9980 // FIXME: This doesn't catch address space mismatches for pointers of
9981 // different nesting levels, like:
9982 // __local int *** a;
9983 // int ** b = a;
9984 // It's not clear how to actually determine when such pointers are
9985 // invalidly incompatible.
9986 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9987 return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
9989 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9991 if (lhptee == rhptee)
9992 return Sema::IncompatibleNestedPointerQualifiers;
9995 // General pointer incompatibility takes priority over qualifiers.
9996 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9997 return Sema::IncompatibleFunctionPointer;
9998 return Sema::IncompatiblePointer;
10000 if (!S.getLangOpts().CPlusPlus &&
10001 S.IsFunctionConversion(ltrans, rtrans, ltrans))
10002 return Sema::IncompatibleFunctionPointer;
10003 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
10004 return Sema::IncompatibleFunctionPointer;
10005 if (S.IsInvalidSMECallConversion(
10006 rtrans, ltrans,
10007 Sema::AArch64SMECallConversionKind::MayDropPreservesZA))
10008 return Sema::IncompatibleFunctionPointer;
10009 return ConvTy;
10012 /// checkBlockPointerTypesForAssignment - This routine determines whether two
10013 /// block pointer types are compatible or whether a block and normal pointer
10014 /// are compatible. It is more restrict than comparing two function pointer
10015 // types.
10016 static Sema::AssignConvertType
10017 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
10018 QualType RHSType) {
10019 assert(LHSType.isCanonical() && "LHS not canonicalized!");
10020 assert(RHSType.isCanonical() && "RHS not canonicalized!");
10022 QualType lhptee, rhptee;
10024 // get the "pointed to" type (ignoring qualifiers at the top level)
10025 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
10026 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
10028 // In C++, the types have to match exactly.
10029 if (S.getLangOpts().CPlusPlus)
10030 return Sema::IncompatibleBlockPointer;
10032 Sema::AssignConvertType ConvTy = Sema::Compatible;
10034 // For blocks we enforce that qualifiers are identical.
10035 Qualifiers LQuals = lhptee.getLocalQualifiers();
10036 Qualifiers RQuals = rhptee.getLocalQualifiers();
10037 if (S.getLangOpts().OpenCL) {
10038 LQuals.removeAddressSpace();
10039 RQuals.removeAddressSpace();
10041 if (LQuals != RQuals)
10042 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
10044 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
10045 // assignment.
10046 // The current behavior is similar to C++ lambdas. A block might be
10047 // assigned to a variable iff its return type and parameters are compatible
10048 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
10049 // an assignment. Presumably it should behave in way that a function pointer
10050 // assignment does in C, so for each parameter and return type:
10051 // * CVR and address space of LHS should be a superset of CVR and address
10052 // space of RHS.
10053 // * unqualified types should be compatible.
10054 if (S.getLangOpts().OpenCL) {
10055 if (!S.Context.typesAreBlockPointerCompatible(
10056 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
10057 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
10058 return Sema::IncompatibleBlockPointer;
10059 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
10060 return Sema::IncompatibleBlockPointer;
10062 return ConvTy;
10065 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
10066 /// for assignment compatibility.
10067 static Sema::AssignConvertType
10068 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
10069 QualType RHSType) {
10070 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
10071 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
10073 if (LHSType->isObjCBuiltinType()) {
10074 // Class is not compatible with ObjC object pointers.
10075 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
10076 !RHSType->isObjCQualifiedClassType())
10077 return Sema::IncompatiblePointer;
10078 return Sema::Compatible;
10080 if (RHSType->isObjCBuiltinType()) {
10081 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
10082 !LHSType->isObjCQualifiedClassType())
10083 return Sema::IncompatiblePointer;
10084 return Sema::Compatible;
10086 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
10087 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
10089 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
10090 // make an exception for id<P>
10091 !LHSType->isObjCQualifiedIdType())
10092 return Sema::CompatiblePointerDiscardsQualifiers;
10094 if (S.Context.typesAreCompatible(LHSType, RHSType))
10095 return Sema::Compatible;
10096 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
10097 return Sema::IncompatibleObjCQualifiedId;
10098 return Sema::IncompatiblePointer;
10101 Sema::AssignConvertType
10102 Sema::CheckAssignmentConstraints(SourceLocation Loc,
10103 QualType LHSType, QualType RHSType) {
10104 // Fake up an opaque expression. We don't actually care about what
10105 // cast operations are required, so if CheckAssignmentConstraints
10106 // adds casts to this they'll be wasted, but fortunately that doesn't
10107 // usually happen on valid code.
10108 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
10109 ExprResult RHSPtr = &RHSExpr;
10110 CastKind K;
10112 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
10115 /// This helper function returns true if QT is a vector type that has element
10116 /// type ElementType.
10117 static bool isVector(QualType QT, QualType ElementType) {
10118 if (const VectorType *VT = QT->getAs<VectorType>())
10119 return VT->getElementType().getCanonicalType() == ElementType;
10120 return false;
10123 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
10124 /// has code to accommodate several GCC extensions when type checking
10125 /// pointers. Here are some objectionable examples that GCC considers warnings:
10127 /// int a, *pint;
10128 /// short *pshort;
10129 /// struct foo *pfoo;
10131 /// pint = pshort; // warning: assignment from incompatible pointer type
10132 /// a = pint; // warning: assignment makes integer from pointer without a cast
10133 /// pint = a; // warning: assignment makes pointer from integer without a cast
10134 /// pint = pfoo; // warning: assignment from incompatible pointer type
10136 /// As a result, the code for dealing with pointers is more complex than the
10137 /// C99 spec dictates.
10139 /// Sets 'Kind' for any result kind except Incompatible.
10140 Sema::AssignConvertType
10141 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
10142 CastKind &Kind, bool ConvertRHS) {
10143 QualType RHSType = RHS.get()->getType();
10144 QualType OrigLHSType = LHSType;
10146 // Get canonical types. We're not formatting these types, just comparing
10147 // them.
10148 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
10149 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
10151 // Common case: no conversion required.
10152 if (LHSType == RHSType) {
10153 Kind = CK_NoOp;
10154 return Compatible;
10157 // If the LHS has an __auto_type, there are no additional type constraints
10158 // to be worried about.
10159 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
10160 if (AT->isGNUAutoType()) {
10161 Kind = CK_NoOp;
10162 return Compatible;
10166 // If we have an atomic type, try a non-atomic assignment, then just add an
10167 // atomic qualification step.
10168 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
10169 Sema::AssignConvertType result =
10170 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
10171 if (result != Compatible)
10172 return result;
10173 if (Kind != CK_NoOp && ConvertRHS)
10174 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
10175 Kind = CK_NonAtomicToAtomic;
10176 return Compatible;
10179 // If the left-hand side is a reference type, then we are in a
10180 // (rare!) case where we've allowed the use of references in C,
10181 // e.g., as a parameter type in a built-in function. In this case,
10182 // just make sure that the type referenced is compatible with the
10183 // right-hand side type. The caller is responsible for adjusting
10184 // LHSType so that the resulting expression does not have reference
10185 // type.
10186 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
10187 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
10188 Kind = CK_LValueBitCast;
10189 return Compatible;
10191 return Incompatible;
10194 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
10195 // to the same ExtVector type.
10196 if (LHSType->isExtVectorType()) {
10197 if (RHSType->isExtVectorType())
10198 return Incompatible;
10199 if (RHSType->isArithmeticType()) {
10200 // CK_VectorSplat does T -> vector T, so first cast to the element type.
10201 if (ConvertRHS)
10202 RHS = prepareVectorSplat(LHSType, RHS.get());
10203 Kind = CK_VectorSplat;
10204 return Compatible;
10208 // Conversions to or from vector type.
10209 if (LHSType->isVectorType() || RHSType->isVectorType()) {
10210 if (LHSType->isVectorType() && RHSType->isVectorType()) {
10211 // Allow assignments of an AltiVec vector type to an equivalent GCC
10212 // vector type and vice versa
10213 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10214 Kind = CK_BitCast;
10215 return Compatible;
10218 // If we are allowing lax vector conversions, and LHS and RHS are both
10219 // vectors, the total size only needs to be the same. This is a bitcast;
10220 // no bits are changed but the result type is different.
10221 if (isLaxVectorConversion(RHSType, LHSType)) {
10222 // The default for lax vector conversions with Altivec vectors will
10223 // change, so if we are converting between vector types where
10224 // at least one is an Altivec vector, emit a warning.
10225 if (Context.getTargetInfo().getTriple().isPPC() &&
10226 anyAltivecTypes(RHSType, LHSType) &&
10227 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10228 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
10229 << RHSType << LHSType;
10230 Kind = CK_BitCast;
10231 return IncompatibleVectors;
10235 // When the RHS comes from another lax conversion (e.g. binops between
10236 // scalars and vectors) the result is canonicalized as a vector. When the
10237 // LHS is also a vector, the lax is allowed by the condition above. Handle
10238 // the case where LHS is a scalar.
10239 if (LHSType->isScalarType()) {
10240 const VectorType *VecType = RHSType->getAs<VectorType>();
10241 if (VecType && VecType->getNumElements() == 1 &&
10242 isLaxVectorConversion(RHSType, LHSType)) {
10243 if (Context.getTargetInfo().getTriple().isPPC() &&
10244 (VecType->getVectorKind() == VectorKind::AltiVecVector ||
10245 VecType->getVectorKind() == VectorKind::AltiVecBool ||
10246 VecType->getVectorKind() == VectorKind::AltiVecPixel))
10247 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
10248 << RHSType << LHSType;
10249 ExprResult *VecExpr = &RHS;
10250 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
10251 Kind = CK_BitCast;
10252 return Compatible;
10256 // Allow assignments between fixed-length and sizeless SVE vectors.
10257 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
10258 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
10259 if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
10260 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
10261 Kind = CK_BitCast;
10262 return Compatible;
10265 // Allow assignments between fixed-length and sizeless RVV vectors.
10266 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
10267 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
10268 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
10269 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
10270 Kind = CK_BitCast;
10271 return Compatible;
10275 return Incompatible;
10278 // Diagnose attempts to convert between __ibm128, __float128 and long double
10279 // where such conversions currently can't be handled.
10280 if (unsupportedTypeConversion(*this, LHSType, RHSType))
10281 return Incompatible;
10283 // Disallow assigning a _Complex to a real type in C++ mode since it simply
10284 // discards the imaginary part.
10285 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
10286 !LHSType->getAs<ComplexType>())
10287 return Incompatible;
10289 // Arithmetic conversions.
10290 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
10291 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
10292 if (ConvertRHS)
10293 Kind = PrepareScalarCast(RHS, LHSType);
10294 return Compatible;
10297 // Conversions to normal pointers.
10298 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
10299 // U* -> T*
10300 if (isa<PointerType>(RHSType)) {
10301 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
10302 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
10303 if (AddrSpaceL != AddrSpaceR)
10304 Kind = CK_AddressSpaceConversion;
10305 else if (Context.hasCvrSimilarType(RHSType, LHSType))
10306 Kind = CK_NoOp;
10307 else
10308 Kind = CK_BitCast;
10309 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
10310 RHS.get()->getBeginLoc());
10313 // int -> T*
10314 if (RHSType->isIntegerType()) {
10315 Kind = CK_IntegralToPointer; // FIXME: null?
10316 return IntToPointer;
10319 // C pointers are not compatible with ObjC object pointers,
10320 // with two exceptions:
10321 if (isa<ObjCObjectPointerType>(RHSType)) {
10322 // - conversions to void*
10323 if (LHSPointer->getPointeeType()->isVoidType()) {
10324 Kind = CK_BitCast;
10325 return Compatible;
10328 // - conversions from 'Class' to the redefinition type
10329 if (RHSType->isObjCClassType() &&
10330 Context.hasSameType(LHSType,
10331 Context.getObjCClassRedefinitionType())) {
10332 Kind = CK_BitCast;
10333 return Compatible;
10336 Kind = CK_BitCast;
10337 return IncompatiblePointer;
10340 // U^ -> void*
10341 if (RHSType->getAs<BlockPointerType>()) {
10342 if (LHSPointer->getPointeeType()->isVoidType()) {
10343 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
10344 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10345 ->getPointeeType()
10346 .getAddressSpace();
10347 Kind =
10348 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10349 return Compatible;
10353 return Incompatible;
10356 // Conversions to block pointers.
10357 if (isa<BlockPointerType>(LHSType)) {
10358 // U^ -> T^
10359 if (RHSType->isBlockPointerType()) {
10360 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
10361 ->getPointeeType()
10362 .getAddressSpace();
10363 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
10364 ->getPointeeType()
10365 .getAddressSpace();
10366 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
10367 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
10370 // int or null -> T^
10371 if (RHSType->isIntegerType()) {
10372 Kind = CK_IntegralToPointer; // FIXME: null
10373 return IntToBlockPointer;
10376 // id -> T^
10377 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
10378 Kind = CK_AnyPointerToBlockPointerCast;
10379 return Compatible;
10382 // void* -> T^
10383 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
10384 if (RHSPT->getPointeeType()->isVoidType()) {
10385 Kind = CK_AnyPointerToBlockPointerCast;
10386 return Compatible;
10389 return Incompatible;
10392 // Conversions to Objective-C pointers.
10393 if (isa<ObjCObjectPointerType>(LHSType)) {
10394 // A* -> B*
10395 if (RHSType->isObjCObjectPointerType()) {
10396 Kind = CK_BitCast;
10397 Sema::AssignConvertType result =
10398 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
10399 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10400 result == Compatible &&
10401 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
10402 result = IncompatibleObjCWeakRef;
10403 return result;
10406 // int or null -> A*
10407 if (RHSType->isIntegerType()) {
10408 Kind = CK_IntegralToPointer; // FIXME: null
10409 return IntToPointer;
10412 // In general, C pointers are not compatible with ObjC object pointers,
10413 // with two exceptions:
10414 if (isa<PointerType>(RHSType)) {
10415 Kind = CK_CPointerToObjCPointerCast;
10417 // - conversions from 'void*'
10418 if (RHSType->isVoidPointerType()) {
10419 return Compatible;
10422 // - conversions to 'Class' from its redefinition type
10423 if (LHSType->isObjCClassType() &&
10424 Context.hasSameType(RHSType,
10425 Context.getObjCClassRedefinitionType())) {
10426 return Compatible;
10429 return IncompatiblePointer;
10432 // Only under strict condition T^ is compatible with an Objective-C pointer.
10433 if (RHSType->isBlockPointerType() &&
10434 LHSType->isBlockCompatibleObjCPointerType(Context)) {
10435 if (ConvertRHS)
10436 maybeExtendBlockObject(RHS);
10437 Kind = CK_BlockPointerToObjCPointerCast;
10438 return Compatible;
10441 return Incompatible;
10444 // Conversion to nullptr_t (C23 only)
10445 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
10446 RHS.get()->isNullPointerConstant(Context,
10447 Expr::NPC_ValueDependentIsNull)) {
10448 // null -> nullptr_t
10449 Kind = CK_NullToPointer;
10450 return Compatible;
10453 // Conversions from pointers that are not covered by the above.
10454 if (isa<PointerType>(RHSType)) {
10455 // T* -> _Bool
10456 if (LHSType == Context.BoolTy) {
10457 Kind = CK_PointerToBoolean;
10458 return Compatible;
10461 // T* -> int
10462 if (LHSType->isIntegerType()) {
10463 Kind = CK_PointerToIntegral;
10464 return PointerToInt;
10467 return Incompatible;
10470 // Conversions from Objective-C pointers that are not covered by the above.
10471 if (isa<ObjCObjectPointerType>(RHSType)) {
10472 // T* -> _Bool
10473 if (LHSType == Context.BoolTy) {
10474 Kind = CK_PointerToBoolean;
10475 return Compatible;
10478 // T* -> int
10479 if (LHSType->isIntegerType()) {
10480 Kind = CK_PointerToIntegral;
10481 return PointerToInt;
10484 return Incompatible;
10487 // struct A -> struct B
10488 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
10489 if (Context.typesAreCompatible(LHSType, RHSType)) {
10490 Kind = CK_NoOp;
10491 return Compatible;
10495 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
10496 Kind = CK_IntToOCLSampler;
10497 return Compatible;
10500 return Incompatible;
10503 /// Constructs a transparent union from an expression that is
10504 /// used to initialize the transparent union.
10505 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
10506 ExprResult &EResult, QualType UnionType,
10507 FieldDecl *Field) {
10508 // Build an initializer list that designates the appropriate member
10509 // of the transparent union.
10510 Expr *E = EResult.get();
10511 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
10512 E, SourceLocation());
10513 Initializer->setType(UnionType);
10514 Initializer->setInitializedFieldInUnion(Field);
10516 // Build a compound literal constructing a value of the transparent
10517 // union type from this initializer list.
10518 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
10519 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10520 VK_PRValue, Initializer, false);
10523 Sema::AssignConvertType
10524 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
10525 ExprResult &RHS) {
10526 QualType RHSType = RHS.get()->getType();
10528 // If the ArgType is a Union type, we want to handle a potential
10529 // transparent_union GCC extension.
10530 const RecordType *UT = ArgType->getAsUnionType();
10531 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
10532 return Incompatible;
10534 // The field to initialize within the transparent union.
10535 RecordDecl *UD = UT->getDecl();
10536 FieldDecl *InitField = nullptr;
10537 // It's compatible if the expression matches any of the fields.
10538 for (auto *it : UD->fields()) {
10539 if (it->getType()->isPointerType()) {
10540 // If the transparent union contains a pointer type, we allow:
10541 // 1) void pointer
10542 // 2) null pointer constant
10543 if (RHSType->isPointerType())
10544 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10545 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
10546 InitField = it;
10547 break;
10550 if (RHS.get()->isNullPointerConstant(Context,
10551 Expr::NPC_ValueDependentIsNull)) {
10552 RHS = ImpCastExprToType(RHS.get(), it->getType(),
10553 CK_NullToPointer);
10554 InitField = it;
10555 break;
10559 CastKind Kind;
10560 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
10561 == Compatible) {
10562 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
10563 InitField = it;
10564 break;
10568 if (!InitField)
10569 return Incompatible;
10571 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
10572 return Compatible;
10575 Sema::AssignConvertType
10576 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
10577 bool Diagnose,
10578 bool DiagnoseCFAudited,
10579 bool ConvertRHS) {
10580 // We need to be able to tell the caller whether we diagnosed a problem, if
10581 // they ask us to issue diagnostics.
10582 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10584 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10585 // we can't avoid *all* modifications at the moment, so we need some somewhere
10586 // to put the updated value.
10587 ExprResult LocalRHS = CallerRHS;
10588 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10590 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10591 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10592 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
10593 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
10594 Diag(RHS.get()->getExprLoc(),
10595 diag::warn_noderef_to_dereferenceable_pointer)
10596 << RHS.get()->getSourceRange();
10601 if (getLangOpts().CPlusPlus) {
10602 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10603 // C++ 5.17p3: If the left operand is not of class type, the
10604 // expression is implicitly converted (C++ 4) to the
10605 // cv-unqualified type of the left operand.
10606 QualType RHSType = RHS.get()->getType();
10607 if (Diagnose) {
10608 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10609 AA_Assigning);
10610 } else {
10611 ImplicitConversionSequence ICS =
10612 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10613 /*SuppressUserConversions=*/false,
10614 AllowedExplicit::None,
10615 /*InOverloadResolution=*/false,
10616 /*CStyle=*/false,
10617 /*AllowObjCWritebackConversion=*/false);
10618 if (ICS.isFailure())
10619 return Incompatible;
10620 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10621 ICS, AA_Assigning);
10623 if (RHS.isInvalid())
10624 return Incompatible;
10625 Sema::AssignConvertType result = Compatible;
10626 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10627 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
10628 result = IncompatibleObjCWeakRef;
10629 return result;
10632 // FIXME: Currently, we fall through and treat C++ classes like C
10633 // structures.
10634 // FIXME: We also fall through for atomics; not sure what should
10635 // happen there, though.
10636 } else if (RHS.get()->getType() == Context.OverloadTy) {
10637 // As a set of extensions to C, we support overloading on functions. These
10638 // functions need to be resolved here.
10639 DeclAccessPair DAP;
10640 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
10641 RHS.get(), LHSType, /*Complain=*/false, DAP))
10642 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
10643 else
10644 return Incompatible;
10647 // This check seems unnatural, however it is necessary to ensure the proper
10648 // conversion of functions/arrays. If the conversion were done for all
10649 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10650 // expressions that suppress this implicit conversion (&, sizeof). This needs
10651 // to happen before we check for null pointer conversions because C does not
10652 // undergo the same implicit conversions as C++ does above (by the calls to
10653 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10654 // lvalue to rvalue cast before checking for null pointer constraints. This
10655 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10657 // Suppress this for references: C++ 8.5.3p5.
10658 if (!LHSType->isReferenceType()) {
10659 // FIXME: We potentially allocate here even if ConvertRHS is false.
10660 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
10661 if (RHS.isInvalid())
10662 return Incompatible;
10665 // The constraints are expressed in terms of the atomic, qualified, or
10666 // unqualified type of the LHS.
10667 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10669 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10670 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10671 if ((LHSTypeAfterConversion->isPointerType() ||
10672 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10673 LHSTypeAfterConversion->isBlockPointerType()) &&
10674 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10675 RHS.get()->isNullPointerConstant(Context,
10676 Expr::NPC_ValueDependentIsNull))) {
10677 if (Diagnose || ConvertRHS) {
10678 CastKind Kind;
10679 CXXCastPath Path;
10680 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
10681 /*IgnoreBaseAccess=*/false, Diagnose);
10682 if (ConvertRHS)
10683 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
10685 return Compatible;
10687 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10688 // unqualified bool, and the right operand is a pointer or its type is
10689 // nullptr_t.
10690 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10691 RHS.get()->getType()->isNullPtrType()) {
10692 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10693 // only handles nullptr -> _Bool due to needing an extra conversion
10694 // step.
10695 // We model this by converting from nullptr -> void * and then let the
10696 // conversion from void * -> _Bool happen naturally.
10697 if (Diagnose || ConvertRHS) {
10698 CastKind Kind;
10699 CXXCastPath Path;
10700 CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path,
10701 /*IgnoreBaseAccess=*/false, Diagnose);
10702 if (ConvertRHS)
10703 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
10704 &Path);
10708 // OpenCL queue_t type assignment.
10709 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10710 Context, Expr::NPC_ValueDependentIsNull)) {
10711 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10712 return Compatible;
10715 CastKind Kind;
10716 Sema::AssignConvertType result =
10717 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10719 // C99 6.5.16.1p2: The value of the right operand is converted to the
10720 // type of the assignment expression.
10721 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10722 // so that we can use references in built-in functions even in C.
10723 // The getNonReferenceType() call makes sure that the resulting expression
10724 // does not have reference type.
10725 if (result != Incompatible && RHS.get()->getType() != LHSType) {
10726 QualType Ty = LHSType.getNonLValueExprType(Context);
10727 Expr *E = RHS.get();
10729 // Check for various Objective-C errors. If we are not reporting
10730 // diagnostics and just checking for errors, e.g., during overload
10731 // resolution, return Incompatible to indicate the failure.
10732 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10733 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
10734 Diagnose, DiagnoseCFAudited) != ACR_okay) {
10735 if (!Diagnose)
10736 return Incompatible;
10738 if (getLangOpts().ObjC &&
10739 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
10740 E->getType(), E, Diagnose) ||
10741 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
10742 if (!Diagnose)
10743 return Incompatible;
10744 // Replace the expression with a corrected version and continue so we
10745 // can find further errors.
10746 RHS = E;
10747 return Compatible;
10750 if (ConvertRHS)
10751 RHS = ImpCastExprToType(E, Ty, Kind);
10754 return result;
10757 namespace {
10758 /// The original operand to an operator, prior to the application of the usual
10759 /// arithmetic conversions and converting the arguments of a builtin operator
10760 /// candidate.
10761 struct OriginalOperand {
10762 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10763 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10764 Op = MTE->getSubExpr();
10765 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10766 Op = BTE->getSubExpr();
10767 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10768 Orig = ICE->getSubExprAsWritten();
10769 Conversion = ICE->getConversionFunction();
10773 QualType getType() const { return Orig->getType(); }
10775 Expr *Orig;
10776 NamedDecl *Conversion;
10780 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10781 ExprResult &RHS) {
10782 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10784 Diag(Loc, diag::err_typecheck_invalid_operands)
10785 << OrigLHS.getType() << OrigRHS.getType()
10786 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10788 // If a user-defined conversion was applied to either of the operands prior
10789 // to applying the built-in operator rules, tell the user about it.
10790 if (OrigLHS.Conversion) {
10791 Diag(OrigLHS.Conversion->getLocation(),
10792 diag::note_typecheck_invalid_operands_converted)
10793 << 0 << LHS.get()->getType();
10795 if (OrigRHS.Conversion) {
10796 Diag(OrigRHS.Conversion->getLocation(),
10797 diag::note_typecheck_invalid_operands_converted)
10798 << 1 << RHS.get()->getType();
10801 return QualType();
10804 // Diagnose cases where a scalar was implicitly converted to a vector and
10805 // diagnose the underlying types. Otherwise, diagnose the error
10806 // as invalid vector logical operands for non-C++ cases.
10807 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10808 ExprResult &RHS) {
10809 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10810 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10812 bool LHSNatVec = LHSType->isVectorType();
10813 bool RHSNatVec = RHSType->isVectorType();
10815 if (!(LHSNatVec && RHSNatVec)) {
10816 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10817 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10818 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10819 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10820 << Vector->getSourceRange();
10821 return QualType();
10824 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10825 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10826 << RHS.get()->getSourceRange();
10828 return QualType();
10831 /// Try to convert a value of non-vector type to a vector type by converting
10832 /// the type to the element type of the vector and then performing a splat.
10833 /// If the language is OpenCL, we only use conversions that promote scalar
10834 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10835 /// for float->int.
10837 /// OpenCL V2.0 6.2.6.p2:
10838 /// An error shall occur if any scalar operand type has greater rank
10839 /// than the type of the vector element.
10841 /// \param scalar - if non-null, actually perform the conversions
10842 /// \return true if the operation fails (but without diagnosing the failure)
10843 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10844 QualType scalarTy,
10845 QualType vectorEltTy,
10846 QualType vectorTy,
10847 unsigned &DiagID) {
10848 // The conversion to apply to the scalar before splatting it,
10849 // if necessary.
10850 CastKind scalarCast = CK_NoOp;
10852 if (vectorEltTy->isIntegralType(S.Context)) {
10853 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10854 (scalarTy->isIntegerType() &&
10855 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10856 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10857 return true;
10859 if (!scalarTy->isIntegralType(S.Context))
10860 return true;
10861 scalarCast = CK_IntegralCast;
10862 } else if (vectorEltTy->isRealFloatingType()) {
10863 if (scalarTy->isRealFloatingType()) {
10864 if (S.getLangOpts().OpenCL &&
10865 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10866 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10867 return true;
10869 scalarCast = CK_FloatingCast;
10871 else if (scalarTy->isIntegralType(S.Context))
10872 scalarCast = CK_IntegralToFloating;
10873 else
10874 return true;
10875 } else {
10876 return true;
10879 // Adjust scalar if desired.
10880 if (scalar) {
10881 if (scalarCast != CK_NoOp)
10882 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10883 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10885 return false;
10888 /// Convert vector E to a vector with the same number of elements but different
10889 /// element type.
10890 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10891 const auto *VecTy = E->getType()->getAs<VectorType>();
10892 assert(VecTy && "Expression E must be a vector");
10893 QualType NewVecTy =
10894 VecTy->isExtVectorType()
10895 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10896 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10897 VecTy->getVectorKind());
10899 // Look through the implicit cast. Return the subexpression if its type is
10900 // NewVecTy.
10901 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10902 if (ICE->getSubExpr()->getType() == NewVecTy)
10903 return ICE->getSubExpr();
10905 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10906 return S.ImpCastExprToType(E, NewVecTy, Cast);
10909 /// Test if a (constant) integer Int can be casted to another integer type
10910 /// IntTy without losing precision.
10911 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10912 QualType OtherIntTy) {
10913 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10915 // Reject cases where the value of the Int is unknown as that would
10916 // possibly cause truncation, but accept cases where the scalar can be
10917 // demoted without loss of precision.
10918 Expr::EvalResult EVResult;
10919 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10920 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10921 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10922 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10924 if (CstInt) {
10925 // If the scalar is constant and is of a higher order and has more active
10926 // bits that the vector element type, reject it.
10927 llvm::APSInt Result = EVResult.Val.getInt();
10928 unsigned NumBits = IntSigned
10929 ? (Result.isNegative() ? Result.getSignificantBits()
10930 : Result.getActiveBits())
10931 : Result.getActiveBits();
10932 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10933 return true;
10935 // If the signedness of the scalar type and the vector element type
10936 // differs and the number of bits is greater than that of the vector
10937 // element reject it.
10938 return (IntSigned != OtherIntSigned &&
10939 NumBits > S.Context.getIntWidth(OtherIntTy));
10942 // Reject cases where the value of the scalar is not constant and it's
10943 // order is greater than that of the vector element type.
10944 return (Order < 0);
10947 /// Test if a (constant) integer Int can be casted to floating point type
10948 /// FloatTy without losing precision.
10949 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10950 QualType FloatTy) {
10951 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10953 // Determine if the integer constant can be expressed as a floating point
10954 // number of the appropriate type.
10955 Expr::EvalResult EVResult;
10956 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10958 uint64_t Bits = 0;
10959 if (CstInt) {
10960 // Reject constants that would be truncated if they were converted to
10961 // the floating point type. Test by simple to/from conversion.
10962 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10963 // could be avoided if there was a convertFromAPInt method
10964 // which could signal back if implicit truncation occurred.
10965 llvm::APSInt Result = EVResult.Val.getInt();
10966 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10967 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10968 llvm::APFloat::rmTowardZero);
10969 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10970 !IntTy->hasSignedIntegerRepresentation());
10971 bool Ignored = false;
10972 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10973 &Ignored);
10974 if (Result != ConvertBack)
10975 return true;
10976 } else {
10977 // Reject types that cannot be fully encoded into the mantissa of
10978 // the float.
10979 Bits = S.Context.getTypeSize(IntTy);
10980 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10981 S.Context.getFloatTypeSemantics(FloatTy));
10982 if (Bits > FloatPrec)
10983 return true;
10986 return false;
10989 /// Attempt to convert and splat Scalar into a vector whose types matches
10990 /// Vector following GCC conversion rules. The rule is that implicit
10991 /// conversion can occur when Scalar can be casted to match Vector's element
10992 /// type without causing truncation of Scalar.
10993 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10994 ExprResult *Vector) {
10995 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10996 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10997 QualType VectorEltTy;
10999 if (const auto *VT = VectorTy->getAs<VectorType>()) {
11000 assert(!isa<ExtVectorType>(VT) &&
11001 "ExtVectorTypes should not be handled here!");
11002 VectorEltTy = VT->getElementType();
11003 } else if (VectorTy->isSveVLSBuiltinType()) {
11004 VectorEltTy =
11005 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
11006 } else {
11007 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
11010 // Reject cases where the vector element type or the scalar element type are
11011 // not integral or floating point types.
11012 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
11013 return true;
11015 // The conversion to apply to the scalar before splatting it,
11016 // if necessary.
11017 CastKind ScalarCast = CK_NoOp;
11019 // Accept cases where the vector elements are integers and the scalar is
11020 // an integer.
11021 // FIXME: Notionally if the scalar was a floating point value with a precise
11022 // integral representation, we could cast it to an appropriate integer
11023 // type and then perform the rest of the checks here. GCC will perform
11024 // this conversion in some cases as determined by the input language.
11025 // We should accept it on a language independent basis.
11026 if (VectorEltTy->isIntegralType(S.Context) &&
11027 ScalarTy->isIntegralType(S.Context) &&
11028 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
11030 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
11031 return true;
11033 ScalarCast = CK_IntegralCast;
11034 } else if (VectorEltTy->isIntegralType(S.Context) &&
11035 ScalarTy->isRealFloatingType()) {
11036 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
11037 ScalarCast = CK_FloatingToIntegral;
11038 else
11039 return true;
11040 } else if (VectorEltTy->isRealFloatingType()) {
11041 if (ScalarTy->isRealFloatingType()) {
11043 // Reject cases where the scalar type is not a constant and has a higher
11044 // Order than the vector element type.
11045 llvm::APFloat Result(0.0);
11047 // Determine whether this is a constant scalar. In the event that the
11048 // value is dependent (and thus cannot be evaluated by the constant
11049 // evaluator), skip the evaluation. This will then diagnose once the
11050 // expression is instantiated.
11051 bool CstScalar = Scalar->get()->isValueDependent() ||
11052 Scalar->get()->EvaluateAsFloat(Result, S.Context);
11053 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
11054 if (!CstScalar && Order < 0)
11055 return true;
11057 // If the scalar cannot be safely casted to the vector element type,
11058 // reject it.
11059 if (CstScalar) {
11060 bool Truncated = false;
11061 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
11062 llvm::APFloat::rmNearestTiesToEven, &Truncated);
11063 if (Truncated)
11064 return true;
11067 ScalarCast = CK_FloatingCast;
11068 } else if (ScalarTy->isIntegralType(S.Context)) {
11069 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
11070 return true;
11072 ScalarCast = CK_IntegralToFloating;
11073 } else
11074 return true;
11075 } else if (ScalarTy->isEnumeralType())
11076 return true;
11078 // Adjust scalar if desired.
11079 if (ScalarCast != CK_NoOp)
11080 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
11081 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
11082 return false;
11085 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
11086 SourceLocation Loc, bool IsCompAssign,
11087 bool AllowBothBool,
11088 bool AllowBoolConversions,
11089 bool AllowBoolOperation,
11090 bool ReportInvalid) {
11091 if (!IsCompAssign) {
11092 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11093 if (LHS.isInvalid())
11094 return QualType();
11096 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11097 if (RHS.isInvalid())
11098 return QualType();
11100 // For conversion purposes, we ignore any qualifiers.
11101 // For example, "const float" and "float" are equivalent.
11102 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
11103 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
11105 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
11106 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
11107 assert(LHSVecType || RHSVecType);
11109 // AltiVec-style "vector bool op vector bool" combinations are allowed
11110 // for some operators but not others.
11111 if (!AllowBothBool && LHSVecType &&
11112 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
11113 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11114 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
11116 // This operation may not be performed on boolean vectors.
11117 if (!AllowBoolOperation &&
11118 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
11119 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
11121 // If the vector types are identical, return.
11122 if (Context.hasSameType(LHSType, RHSType))
11123 return Context.getCommonSugaredType(LHSType, RHSType);
11125 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
11126 if (LHSVecType && RHSVecType &&
11127 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
11128 if (isa<ExtVectorType>(LHSVecType)) {
11129 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11130 return LHSType;
11133 if (!IsCompAssign)
11134 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11135 return RHSType;
11138 // AllowBoolConversions says that bool and non-bool AltiVec vectors
11139 // can be mixed, with the result being the non-bool type. The non-bool
11140 // operand must have integer element type.
11141 if (AllowBoolConversions && LHSVecType && RHSVecType &&
11142 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
11143 (Context.getTypeSize(LHSVecType->getElementType()) ==
11144 Context.getTypeSize(RHSVecType->getElementType()))) {
11145 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
11146 LHSVecType->getElementType()->isIntegerType() &&
11147 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
11148 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11149 return LHSType;
11151 if (!IsCompAssign &&
11152 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
11153 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
11154 RHSVecType->getElementType()->isIntegerType()) {
11155 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11156 return RHSType;
11160 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
11161 // invalid since the ambiguity can affect the ABI.
11162 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
11163 unsigned &SVEorRVV) {
11164 const VectorType *VecType = SecondType->getAs<VectorType>();
11165 SVEorRVV = 0;
11166 if (FirstType->isSizelessBuiltinType() && VecType) {
11167 if (VecType->getVectorKind() == VectorKind::SveFixedLengthData ||
11168 VecType->getVectorKind() == VectorKind::SveFixedLengthPredicate)
11169 return true;
11170 if (VecType->getVectorKind() == VectorKind::RVVFixedLengthData) {
11171 SVEorRVV = 1;
11172 return true;
11176 return false;
11179 unsigned SVEorRVV;
11180 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
11181 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
11182 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
11183 << SVEorRVV << LHSType << RHSType;
11184 return QualType();
11187 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
11188 // invalid since the ambiguity can affect the ABI.
11189 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
11190 unsigned &SVEorRVV) {
11191 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
11192 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
11194 SVEorRVV = 0;
11195 if (FirstVecType && SecondVecType) {
11196 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
11197 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
11198 SecondVecType->getVectorKind() ==
11199 VectorKind::SveFixedLengthPredicate)
11200 return true;
11201 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData) {
11202 SVEorRVV = 1;
11203 return true;
11206 return false;
11209 if (SecondVecType &&
11210 SecondVecType->getVectorKind() == VectorKind::Generic) {
11211 if (FirstType->isSVESizelessBuiltinType())
11212 return true;
11213 if (FirstType->isRVVSizelessBuiltinType()) {
11214 SVEorRVV = 1;
11215 return true;
11219 return false;
11222 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
11223 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
11224 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
11225 << SVEorRVV << LHSType << RHSType;
11226 return QualType();
11229 // If there's a vector type and a scalar, try to convert the scalar to
11230 // the vector element type and splat.
11231 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
11232 if (!RHSVecType) {
11233 if (isa<ExtVectorType>(LHSVecType)) {
11234 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
11235 LHSVecType->getElementType(), LHSType,
11236 DiagID))
11237 return LHSType;
11238 } else {
11239 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
11240 return LHSType;
11243 if (!LHSVecType) {
11244 if (isa<ExtVectorType>(RHSVecType)) {
11245 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
11246 LHSType, RHSVecType->getElementType(),
11247 RHSType, DiagID))
11248 return RHSType;
11249 } else {
11250 if (LHS.get()->isLValue() ||
11251 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
11252 return RHSType;
11256 // FIXME: The code below also handles conversion between vectors and
11257 // non-scalars, we should break this down into fine grained specific checks
11258 // and emit proper diagnostics.
11259 QualType VecType = LHSVecType ? LHSType : RHSType;
11260 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
11261 QualType OtherType = LHSVecType ? RHSType : LHSType;
11262 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
11263 if (isLaxVectorConversion(OtherType, VecType)) {
11264 if (Context.getTargetInfo().getTriple().isPPC() &&
11265 anyAltivecTypes(RHSType, LHSType) &&
11266 !Context.areCompatibleVectorTypes(RHSType, LHSType))
11267 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
11268 // If we're allowing lax vector conversions, only the total (data) size
11269 // needs to be the same. For non compound assignment, if one of the types is
11270 // scalar, the result is always the vector type.
11271 if (!IsCompAssign) {
11272 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
11273 return VecType;
11274 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
11275 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
11276 // type. Note that this is already done by non-compound assignments in
11277 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
11278 // <1 x T> -> T. The result is also a vector type.
11279 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
11280 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
11281 ExprResult *RHSExpr = &RHS;
11282 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
11283 return VecType;
11287 // Okay, the expression is invalid.
11289 // If there's a non-vector, non-real operand, diagnose that.
11290 if ((!RHSVecType && !RHSType->isRealType()) ||
11291 (!LHSVecType && !LHSType->isRealType())) {
11292 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
11293 << LHSType << RHSType
11294 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11295 return QualType();
11298 // OpenCL V1.1 6.2.6.p1:
11299 // If the operands are of more than one vector type, then an error shall
11300 // occur. Implicit conversions between vector types are not permitted, per
11301 // section 6.2.1.
11302 if (getLangOpts().OpenCL &&
11303 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
11304 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
11305 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
11306 << RHSType;
11307 return QualType();
11311 // If there is a vector type that is not a ExtVector and a scalar, we reach
11312 // this point if scalar could not be converted to the vector's element type
11313 // without truncation.
11314 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
11315 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
11316 QualType Scalar = LHSVecType ? RHSType : LHSType;
11317 QualType Vector = LHSVecType ? LHSType : RHSType;
11318 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
11319 Diag(Loc,
11320 diag::err_typecheck_vector_not_convertable_implict_truncation)
11321 << ScalarOrVector << Scalar << Vector;
11323 return QualType();
11326 // Otherwise, use the generic diagnostic.
11327 Diag(Loc, DiagID)
11328 << LHSType << RHSType
11329 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11330 return QualType();
11333 QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
11334 SourceLocation Loc,
11335 bool IsCompAssign,
11336 ArithConvKind OperationKind) {
11337 if (!IsCompAssign) {
11338 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11339 if (LHS.isInvalid())
11340 return QualType();
11342 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11343 if (RHS.isInvalid())
11344 return QualType();
11346 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
11347 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
11349 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11350 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11352 unsigned DiagID = diag::err_typecheck_invalid_operands;
11353 if ((OperationKind == ACK_Arithmetic) &&
11354 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11355 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
11356 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11357 << RHS.get()->getSourceRange();
11358 return QualType();
11361 if (Context.hasSameType(LHSType, RHSType))
11362 return LHSType;
11364 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
11365 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
11366 return LHSType;
11368 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
11369 if (LHS.get()->isLValue() ||
11370 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
11371 return RHSType;
11374 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
11375 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
11376 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
11377 << LHSType << RHSType << LHS.get()->getSourceRange()
11378 << RHS.get()->getSourceRange();
11379 return QualType();
11382 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11383 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11384 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
11385 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11386 << LHSType << RHSType << LHS.get()->getSourceRange()
11387 << RHS.get()->getSourceRange();
11388 return QualType();
11391 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
11392 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
11393 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
11394 bool ScalarOrVector =
11395 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
11397 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
11398 << ScalarOrVector << Scalar << Vector;
11400 return QualType();
11403 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11404 << RHS.get()->getSourceRange();
11405 return QualType();
11408 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
11409 // expression. These are mainly cases where the null pointer is used as an
11410 // integer instead of a pointer.
11411 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
11412 SourceLocation Loc, bool IsCompare) {
11413 // The canonical way to check for a GNU null is with isNullPointerConstant,
11414 // but we use a bit of a hack here for speed; this is a relatively
11415 // hot path, and isNullPointerConstant is slow.
11416 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
11417 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
11419 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
11421 // Avoid analyzing cases where the result will either be invalid (and
11422 // diagnosed as such) or entirely valid and not something to warn about.
11423 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
11424 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
11425 return;
11427 // Comparison operations would not make sense with a null pointer no matter
11428 // what the other expression is.
11429 if (!IsCompare) {
11430 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
11431 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
11432 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
11433 return;
11436 // The rest of the operations only make sense with a null pointer
11437 // if the other expression is a pointer.
11438 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
11439 NonNullType->canDecayToPointerType())
11440 return;
11442 S.Diag(Loc, diag::warn_null_in_comparison_operation)
11443 << LHSNull /* LHS is NULL */ << NonNullType
11444 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11447 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
11448 SourceLocation Loc) {
11449 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
11450 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
11451 if (!LUE || !RUE)
11452 return;
11453 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11454 RUE->getKind() != UETT_SizeOf)
11455 return;
11457 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11458 QualType LHSTy = LHSArg->getType();
11459 QualType RHSTy;
11461 if (RUE->isArgumentType())
11462 RHSTy = RUE->getArgumentType().getNonReferenceType();
11463 else
11464 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11466 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11467 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
11468 return;
11470 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11471 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11472 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11473 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
11474 << LHSArgDecl;
11476 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
11477 QualType ArrayElemTy = ArrayTy->getElementType();
11478 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
11479 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11480 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11481 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
11482 return;
11483 S.Diag(Loc, diag::warn_division_sizeof_array)
11484 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11485 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11486 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11487 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
11488 << LHSArgDecl;
11491 S.Diag(Loc, diag::note_precedence_silence) << RHS;
11495 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
11496 ExprResult &RHS,
11497 SourceLocation Loc, bool IsDiv) {
11498 // Check for division/remainder by zero.
11499 Expr::EvalResult RHSValue;
11500 if (!RHS.get()->isValueDependent() &&
11501 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
11502 RHSValue.Val.getInt() == 0)
11503 S.DiagRuntimeBehavior(Loc, RHS.get(),
11504 S.PDiag(diag::warn_remainder_division_by_zero)
11505 << IsDiv << RHS.get()->getSourceRange());
11508 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
11509 SourceLocation Loc,
11510 bool IsCompAssign, bool IsDiv) {
11511 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11513 QualType LHSTy = LHS.get()->getType();
11514 QualType RHSTy = RHS.get()->getType();
11515 if (LHSTy->isVectorType() || RHSTy->isVectorType())
11516 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11517 /*AllowBothBool*/ getLangOpts().AltiVec,
11518 /*AllowBoolConversions*/ false,
11519 /*AllowBooleanOperation*/ false,
11520 /*ReportInvalid*/ true);
11521 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
11522 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11523 ACK_Arithmetic);
11524 if (!IsDiv &&
11525 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11526 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11527 // For division, only matrix-by-scalar is supported. Other combinations with
11528 // matrix types are invalid.
11529 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11530 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11532 QualType compType = UsualArithmeticConversions(
11533 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
11534 if (LHS.isInvalid() || RHS.isInvalid())
11535 return QualType();
11538 if (compType.isNull() || !compType->isArithmeticType())
11539 return InvalidOperands(Loc, LHS, RHS);
11540 if (IsDiv) {
11541 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
11542 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
11544 return compType;
11547 QualType Sema::CheckRemainderOperands(
11548 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11549 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11551 if (LHS.get()->getType()->isVectorType() ||
11552 RHS.get()->getType()->isVectorType()) {
11553 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11554 RHS.get()->getType()->hasIntegerRepresentation())
11555 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11556 /*AllowBothBool*/ getLangOpts().AltiVec,
11557 /*AllowBoolConversions*/ false,
11558 /*AllowBooleanOperation*/ false,
11559 /*ReportInvalid*/ true);
11560 return InvalidOperands(Loc, LHS, RHS);
11563 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11564 RHS.get()->getType()->isSveVLSBuiltinType()) {
11565 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11566 RHS.get()->getType()->hasIntegerRepresentation())
11567 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11568 ACK_Arithmetic);
11570 return InvalidOperands(Loc, LHS, RHS);
11573 QualType compType = UsualArithmeticConversions(
11574 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
11575 if (LHS.isInvalid() || RHS.isInvalid())
11576 return QualType();
11578 if (compType.isNull() || !compType->isIntegerType())
11579 return InvalidOperands(Loc, LHS, RHS);
11580 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
11581 return compType;
11584 /// Diagnose invalid arithmetic on two void pointers.
11585 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
11586 Expr *LHSExpr, Expr *RHSExpr) {
11587 S.Diag(Loc, S.getLangOpts().CPlusPlus
11588 ? diag::err_typecheck_pointer_arith_void_type
11589 : diag::ext_gnu_void_ptr)
11590 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11591 << RHSExpr->getSourceRange();
11594 /// Diagnose invalid arithmetic on a void pointer.
11595 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
11596 Expr *Pointer) {
11597 S.Diag(Loc, S.getLangOpts().CPlusPlus
11598 ? diag::err_typecheck_pointer_arith_void_type
11599 : diag::ext_gnu_void_ptr)
11600 << 0 /* one pointer */ << Pointer->getSourceRange();
11603 /// Diagnose invalid arithmetic on a null pointer.
11605 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11606 /// idiom, which we recognize as a GNU extension.
11608 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
11609 Expr *Pointer, bool IsGNUIdiom) {
11610 if (IsGNUIdiom)
11611 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
11612 << Pointer->getSourceRange();
11613 else
11614 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
11615 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11618 /// Diagnose invalid subraction on a null pointer.
11620 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
11621 Expr *Pointer, bool BothNull) {
11622 // Null - null is valid in C++ [expr.add]p7
11623 if (BothNull && S.getLangOpts().CPlusPlus)
11624 return;
11626 // Is this s a macro from a system header?
11627 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
11628 return;
11630 S.DiagRuntimeBehavior(Loc, Pointer,
11631 S.PDiag(diag::warn_pointer_sub_null_ptr)
11632 << S.getLangOpts().CPlusPlus
11633 << Pointer->getSourceRange());
11636 /// Diagnose invalid arithmetic on two function pointers.
11637 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
11638 Expr *LHS, Expr *RHS) {
11639 assert(LHS->getType()->isAnyPointerType());
11640 assert(RHS->getType()->isAnyPointerType());
11641 S.Diag(Loc, S.getLangOpts().CPlusPlus
11642 ? diag::err_typecheck_pointer_arith_function_type
11643 : diag::ext_gnu_ptr_func_arith)
11644 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11645 // We only show the second type if it differs from the first.
11646 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
11647 RHS->getType())
11648 << RHS->getType()->getPointeeType()
11649 << LHS->getSourceRange() << RHS->getSourceRange();
11652 /// Diagnose invalid arithmetic on a function pointer.
11653 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
11654 Expr *Pointer) {
11655 assert(Pointer->getType()->isAnyPointerType());
11656 S.Diag(Loc, S.getLangOpts().CPlusPlus
11657 ? diag::err_typecheck_pointer_arith_function_type
11658 : diag::ext_gnu_ptr_func_arith)
11659 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11660 << 0 /* one pointer, so only one type */
11661 << Pointer->getSourceRange();
11664 /// Emit error if Operand is incomplete pointer type
11666 /// \returns True if pointer has incomplete type
11667 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
11668 Expr *Operand) {
11669 QualType ResType = Operand->getType();
11670 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11671 ResType = ResAtomicType->getValueType();
11673 assert(ResType->isAnyPointerType() && !ResType->isDependentType());
11674 QualType PointeeTy = ResType->getPointeeType();
11675 return S.RequireCompleteSizedType(
11676 Loc, PointeeTy,
11677 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11678 Operand->getSourceRange());
11681 /// Check the validity of an arithmetic pointer operand.
11683 /// If the operand has pointer type, this code will check for pointer types
11684 /// which are invalid in arithmetic operations. These will be diagnosed
11685 /// appropriately, including whether or not the use is supported as an
11686 /// extension.
11688 /// \returns True when the operand is valid to use (even if as an extension).
11689 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
11690 Expr *Operand) {
11691 QualType ResType = Operand->getType();
11692 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11693 ResType = ResAtomicType->getValueType();
11695 if (!ResType->isAnyPointerType()) return true;
11697 QualType PointeeTy = ResType->getPointeeType();
11698 if (PointeeTy->isVoidType()) {
11699 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
11700 return !S.getLangOpts().CPlusPlus;
11702 if (PointeeTy->isFunctionType()) {
11703 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
11704 return !S.getLangOpts().CPlusPlus;
11707 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11709 return true;
11712 /// Check the validity of a binary arithmetic operation w.r.t. pointer
11713 /// operands.
11715 /// This routine will diagnose any invalid arithmetic on pointer operands much
11716 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
11717 /// for emitting a single diagnostic even for operations where both LHS and RHS
11718 /// are (potentially problematic) pointers.
11720 /// \returns True when the operand is valid to use (even if as an extension).
11721 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
11722 Expr *LHSExpr, Expr *RHSExpr) {
11723 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11724 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11725 if (!isLHSPointer && !isRHSPointer) return true;
11727 QualType LHSPointeeTy, RHSPointeeTy;
11728 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11729 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11731 // if both are pointers check if operation is valid wrt address spaces
11732 if (isLHSPointer && isRHSPointer) {
11733 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
11734 S.Diag(Loc,
11735 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11736 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11737 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11738 return false;
11742 // Check for arithmetic on pointers to incomplete types.
11743 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11744 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11745 if (isLHSVoidPtr || isRHSVoidPtr) {
11746 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
11747 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
11748 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11750 return !S.getLangOpts().CPlusPlus;
11753 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11754 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11755 if (isLHSFuncPtr || isRHSFuncPtr) {
11756 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
11757 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11758 RHSExpr);
11759 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
11761 return !S.getLangOpts().CPlusPlus;
11764 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11765 return false;
11766 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11767 return false;
11769 return true;
11772 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11773 /// literal.
11774 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
11775 Expr *LHSExpr, Expr *RHSExpr) {
11776 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11777 Expr* IndexExpr = RHSExpr;
11778 if (!StrExpr) {
11779 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11780 IndexExpr = LHSExpr;
11783 bool IsStringPlusInt = StrExpr &&
11784 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
11785 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11786 return;
11788 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11789 Self.Diag(OpLoc, diag::warn_string_plus_int)
11790 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11792 // Only print a fixit for "str" + int, not for int + "str".
11793 if (IndexExpr == RHSExpr) {
11794 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11795 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11796 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11797 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11798 << FixItHint::CreateInsertion(EndLoc, "]");
11799 } else
11800 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11803 /// Emit a warning when adding a char literal to a string.
11804 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11805 Expr *LHSExpr, Expr *RHSExpr) {
11806 const Expr *StringRefExpr = LHSExpr;
11807 const CharacterLiteral *CharExpr =
11808 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11810 if (!CharExpr) {
11811 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11812 StringRefExpr = RHSExpr;
11815 if (!CharExpr || !StringRefExpr)
11816 return;
11818 const QualType StringType = StringRefExpr->getType();
11820 // Return if not a PointerType.
11821 if (!StringType->isAnyPointerType())
11822 return;
11824 // Return if not a CharacterType.
11825 if (!StringType->getPointeeType()->isAnyCharacterType())
11826 return;
11828 ASTContext &Ctx = Self.getASTContext();
11829 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11831 const QualType CharType = CharExpr->getType();
11832 if (!CharType->isAnyCharacterType() &&
11833 CharType->isIntegerType() &&
11834 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11835 Self.Diag(OpLoc, diag::warn_string_plus_char)
11836 << DiagRange << Ctx.CharTy;
11837 } else {
11838 Self.Diag(OpLoc, diag::warn_string_plus_char)
11839 << DiagRange << CharExpr->getType();
11842 // Only print a fixit for str + char, not for char + str.
11843 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11844 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11845 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11846 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11847 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11848 << FixItHint::CreateInsertion(EndLoc, "]");
11849 } else {
11850 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11854 /// Emit error when two pointers are incompatible.
11855 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11856 Expr *LHSExpr, Expr *RHSExpr) {
11857 assert(LHSExpr->getType()->isAnyPointerType());
11858 assert(RHSExpr->getType()->isAnyPointerType());
11859 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11860 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11861 << RHSExpr->getSourceRange();
11864 // C99 6.5.6
11865 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11866 SourceLocation Loc, BinaryOperatorKind Opc,
11867 QualType* CompLHSTy) {
11868 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11870 if (LHS.get()->getType()->isVectorType() ||
11871 RHS.get()->getType()->isVectorType()) {
11872 QualType compType =
11873 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11874 /*AllowBothBool*/ getLangOpts().AltiVec,
11875 /*AllowBoolConversions*/ getLangOpts().ZVector,
11876 /*AllowBooleanOperation*/ false,
11877 /*ReportInvalid*/ true);
11878 if (CompLHSTy) *CompLHSTy = compType;
11879 return compType;
11882 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11883 RHS.get()->getType()->isSveVLSBuiltinType()) {
11884 QualType compType =
11885 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11886 if (CompLHSTy)
11887 *CompLHSTy = compType;
11888 return compType;
11891 if (LHS.get()->getType()->isConstantMatrixType() ||
11892 RHS.get()->getType()->isConstantMatrixType()) {
11893 QualType compType =
11894 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11895 if (CompLHSTy)
11896 *CompLHSTy = compType;
11897 return compType;
11900 QualType compType = UsualArithmeticConversions(
11901 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11902 if (LHS.isInvalid() || RHS.isInvalid())
11903 return QualType();
11905 // Diagnose "string literal" '+' int and string '+' "char literal".
11906 if (Opc == BO_Add) {
11907 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11908 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11911 // handle the common case first (both operands are arithmetic).
11912 if (!compType.isNull() && compType->isArithmeticType()) {
11913 if (CompLHSTy) *CompLHSTy = compType;
11914 return compType;
11917 // Type-checking. Ultimately the pointer's going to be in PExp;
11918 // note that we bias towards the LHS being the pointer.
11919 Expr *PExp = LHS.get(), *IExp = RHS.get();
11921 bool isObjCPointer;
11922 if (PExp->getType()->isPointerType()) {
11923 isObjCPointer = false;
11924 } else if (PExp->getType()->isObjCObjectPointerType()) {
11925 isObjCPointer = true;
11926 } else {
11927 std::swap(PExp, IExp);
11928 if (PExp->getType()->isPointerType()) {
11929 isObjCPointer = false;
11930 } else if (PExp->getType()->isObjCObjectPointerType()) {
11931 isObjCPointer = true;
11932 } else {
11933 return InvalidOperands(Loc, LHS, RHS);
11936 assert(PExp->getType()->isAnyPointerType());
11938 if (!IExp->getType()->isIntegerType())
11939 return InvalidOperands(Loc, LHS, RHS);
11941 // Adding to a null pointer results in undefined behavior.
11942 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11943 Context, Expr::NPC_ValueDependentIsNotNull)) {
11944 // In C++ adding zero to a null pointer is defined.
11945 Expr::EvalResult KnownVal;
11946 if (!getLangOpts().CPlusPlus ||
11947 (!IExp->isValueDependent() &&
11948 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11949 KnownVal.Val.getInt() != 0))) {
11950 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11951 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11952 Context, BO_Add, PExp, IExp);
11953 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11957 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11958 return QualType();
11960 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11961 return QualType();
11963 // Check array bounds for pointer arithemtic
11964 CheckArrayAccess(PExp, IExp);
11966 if (CompLHSTy) {
11967 QualType LHSTy = Context.isPromotableBitField(LHS.get());
11968 if (LHSTy.isNull()) {
11969 LHSTy = LHS.get()->getType();
11970 if (Context.isPromotableIntegerType(LHSTy))
11971 LHSTy = Context.getPromotedIntegerType(LHSTy);
11973 *CompLHSTy = LHSTy;
11976 return PExp->getType();
11979 // C99 6.5.6
11980 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11981 SourceLocation Loc,
11982 QualType* CompLHSTy) {
11983 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11985 if (LHS.get()->getType()->isVectorType() ||
11986 RHS.get()->getType()->isVectorType()) {
11987 QualType compType =
11988 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11989 /*AllowBothBool*/ getLangOpts().AltiVec,
11990 /*AllowBoolConversions*/ getLangOpts().ZVector,
11991 /*AllowBooleanOperation*/ false,
11992 /*ReportInvalid*/ true);
11993 if (CompLHSTy) *CompLHSTy = compType;
11994 return compType;
11997 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11998 RHS.get()->getType()->isSveVLSBuiltinType()) {
11999 QualType compType =
12000 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
12001 if (CompLHSTy)
12002 *CompLHSTy = compType;
12003 return compType;
12006 if (LHS.get()->getType()->isConstantMatrixType() ||
12007 RHS.get()->getType()->isConstantMatrixType()) {
12008 QualType compType =
12009 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
12010 if (CompLHSTy)
12011 *CompLHSTy = compType;
12012 return compType;
12015 QualType compType = UsualArithmeticConversions(
12016 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
12017 if (LHS.isInvalid() || RHS.isInvalid())
12018 return QualType();
12020 // Enforce type constraints: C99 6.5.6p3.
12022 // Handle the common case first (both operands are arithmetic).
12023 if (!compType.isNull() && compType->isArithmeticType()) {
12024 if (CompLHSTy) *CompLHSTy = compType;
12025 return compType;
12028 // Either ptr - int or ptr - ptr.
12029 if (LHS.get()->getType()->isAnyPointerType()) {
12030 QualType lpointee = LHS.get()->getType()->getPointeeType();
12032 // Diagnose bad cases where we step over interface counts.
12033 if (LHS.get()->getType()->isObjCObjectPointerType() &&
12034 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
12035 return QualType();
12037 // The result type of a pointer-int computation is the pointer type.
12038 if (RHS.get()->getType()->isIntegerType()) {
12039 // Subtracting from a null pointer should produce a warning.
12040 // The last argument to the diagnose call says this doesn't match the
12041 // GNU int-to-pointer idiom.
12042 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
12043 Expr::NPC_ValueDependentIsNotNull)) {
12044 // In C++ adding zero to a null pointer is defined.
12045 Expr::EvalResult KnownVal;
12046 if (!getLangOpts().CPlusPlus ||
12047 (!RHS.get()->isValueDependent() &&
12048 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
12049 KnownVal.Val.getInt() != 0))) {
12050 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
12054 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
12055 return QualType();
12057 // Check array bounds for pointer arithemtic
12058 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
12059 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
12061 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
12062 return LHS.get()->getType();
12065 // Handle pointer-pointer subtractions.
12066 if (const PointerType *RHSPTy
12067 = RHS.get()->getType()->getAs<PointerType>()) {
12068 QualType rpointee = RHSPTy->getPointeeType();
12070 if (getLangOpts().CPlusPlus) {
12071 // Pointee types must be the same: C++ [expr.add]
12072 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
12073 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
12075 } else {
12076 // Pointee types must be compatible C99 6.5.6p3
12077 if (!Context.typesAreCompatible(
12078 Context.getCanonicalType(lpointee).getUnqualifiedType(),
12079 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
12080 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
12081 return QualType();
12085 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
12086 LHS.get(), RHS.get()))
12087 return QualType();
12089 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
12090 Context, Expr::NPC_ValueDependentIsNotNull);
12091 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
12092 Context, Expr::NPC_ValueDependentIsNotNull);
12094 // Subtracting nullptr or from nullptr is suspect
12095 if (LHSIsNullPtr)
12096 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
12097 if (RHSIsNullPtr)
12098 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
12100 // The pointee type may have zero size. As an extension, a structure or
12101 // union may have zero size or an array may have zero length. In this
12102 // case subtraction does not make sense.
12103 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
12104 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
12105 if (ElementSize.isZero()) {
12106 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
12107 << rpointee.getUnqualifiedType()
12108 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12112 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
12113 return Context.getPointerDiffType();
12117 return InvalidOperands(Loc, LHS, RHS);
12120 static bool isScopedEnumerationType(QualType T) {
12121 if (const EnumType *ET = T->getAs<EnumType>())
12122 return ET->getDecl()->isScoped();
12123 return false;
12126 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
12127 SourceLocation Loc, BinaryOperatorKind Opc,
12128 QualType LHSType) {
12129 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
12130 // so skip remaining warnings as we don't want to modify values within Sema.
12131 if (S.getLangOpts().OpenCL)
12132 return;
12134 // Check right/shifter operand
12135 Expr::EvalResult RHSResult;
12136 if (RHS.get()->isValueDependent() ||
12137 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
12138 return;
12139 llvm::APSInt Right = RHSResult.Val.getInt();
12141 if (Right.isNegative()) {
12142 S.DiagRuntimeBehavior(Loc, RHS.get(),
12143 S.PDiag(diag::warn_shift_negative)
12144 << RHS.get()->getSourceRange());
12145 return;
12148 QualType LHSExprType = LHS.get()->getType();
12149 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
12150 if (LHSExprType->isBitIntType())
12151 LeftSize = S.Context.getIntWidth(LHSExprType);
12152 else if (LHSExprType->isFixedPointType()) {
12153 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
12154 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
12156 if (Right.uge(LeftSize)) {
12157 S.DiagRuntimeBehavior(Loc, RHS.get(),
12158 S.PDiag(diag::warn_shift_gt_typewidth)
12159 << RHS.get()->getSourceRange());
12160 return;
12163 // FIXME: We probably need to handle fixed point types specially here.
12164 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
12165 return;
12167 // When left shifting an ICE which is signed, we can check for overflow which
12168 // according to C++ standards prior to C++2a has undefined behavior
12169 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
12170 // more than the maximum value representable in the result type, so never
12171 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
12172 // expression is still probably a bug.)
12173 Expr::EvalResult LHSResult;
12174 if (LHS.get()->isValueDependent() ||
12175 LHSType->hasUnsignedIntegerRepresentation() ||
12176 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
12177 return;
12178 llvm::APSInt Left = LHSResult.Val.getInt();
12180 // Don't warn if signed overflow is defined, then all the rest of the
12181 // diagnostics will not be triggered because the behavior is defined.
12182 // Also don't warn in C++20 mode (and newer), as signed left shifts
12183 // always wrap and never overflow.
12184 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
12185 return;
12187 // If LHS does not have a non-negative value then, the
12188 // behavior is undefined before C++2a. Warn about it.
12189 if (Left.isNegative()) {
12190 S.DiagRuntimeBehavior(Loc, LHS.get(),
12191 S.PDiag(diag::warn_shift_lhs_negative)
12192 << LHS.get()->getSourceRange());
12193 return;
12196 llvm::APInt ResultBits =
12197 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
12198 if (ResultBits.ule(LeftSize))
12199 return;
12200 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
12201 Result = Result.shl(Right);
12203 // Print the bit representation of the signed integer as an unsigned
12204 // hexadecimal number.
12205 SmallString<40> HexResult;
12206 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
12208 // If we are only missing a sign bit, this is less likely to result in actual
12209 // bugs -- if the result is cast back to an unsigned type, it will have the
12210 // expected value. Thus we place this behind a different warning that can be
12211 // turned off separately if needed.
12212 if (ResultBits - 1 == LeftSize) {
12213 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
12214 << HexResult << LHSType
12215 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12216 return;
12219 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
12220 << HexResult.str() << Result.getSignificantBits() << LHSType
12221 << Left.getBitWidth() << LHS.get()->getSourceRange()
12222 << RHS.get()->getSourceRange();
12225 /// Return the resulting type when a vector is shifted
12226 /// by a scalar or vector shift amount.
12227 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
12228 SourceLocation Loc, bool IsCompAssign) {
12229 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
12230 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
12231 !LHS.get()->getType()->isVectorType()) {
12232 S.Diag(Loc, diag::err_shift_rhs_only_vector)
12233 << RHS.get()->getType() << LHS.get()->getType()
12234 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12235 return QualType();
12238 if (!IsCompAssign) {
12239 LHS = S.UsualUnaryConversions(LHS.get());
12240 if (LHS.isInvalid()) return QualType();
12243 RHS = S.UsualUnaryConversions(RHS.get());
12244 if (RHS.isInvalid()) return QualType();
12246 QualType LHSType = LHS.get()->getType();
12247 // Note that LHS might be a scalar because the routine calls not only in
12248 // OpenCL case.
12249 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
12250 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
12252 // Note that RHS might not be a vector.
12253 QualType RHSType = RHS.get()->getType();
12254 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
12255 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
12257 // Do not allow shifts for boolean vectors.
12258 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
12259 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
12260 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12261 << LHS.get()->getType() << RHS.get()->getType()
12262 << LHS.get()->getSourceRange();
12263 return QualType();
12266 // The operands need to be integers.
12267 if (!LHSEleType->isIntegerType()) {
12268 S.Diag(Loc, diag::err_typecheck_expect_int)
12269 << LHS.get()->getType() << LHS.get()->getSourceRange();
12270 return QualType();
12273 if (!RHSEleType->isIntegerType()) {
12274 S.Diag(Loc, diag::err_typecheck_expect_int)
12275 << RHS.get()->getType() << RHS.get()->getSourceRange();
12276 return QualType();
12279 if (!LHSVecTy) {
12280 assert(RHSVecTy);
12281 if (IsCompAssign)
12282 return RHSType;
12283 if (LHSEleType != RHSEleType) {
12284 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
12285 LHSEleType = RHSEleType;
12287 QualType VecTy =
12288 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
12289 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
12290 LHSType = VecTy;
12291 } else if (RHSVecTy) {
12292 // OpenCL v1.1 s6.3.j says that for vector types, the operators
12293 // are applied component-wise. So if RHS is a vector, then ensure
12294 // that the number of elements is the same as LHS...
12295 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
12296 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12297 << LHS.get()->getType() << RHS.get()->getType()
12298 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12299 return QualType();
12301 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
12302 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
12303 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
12304 if (LHSBT != RHSBT &&
12305 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
12306 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
12307 << LHS.get()->getType() << RHS.get()->getType()
12308 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12311 } else {
12312 // ...else expand RHS to match the number of elements in LHS.
12313 QualType VecTy =
12314 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
12315 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12318 return LHSType;
12321 static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
12322 ExprResult &RHS, SourceLocation Loc,
12323 bool IsCompAssign) {
12324 if (!IsCompAssign) {
12325 LHS = S.UsualUnaryConversions(LHS.get());
12326 if (LHS.isInvalid())
12327 return QualType();
12330 RHS = S.UsualUnaryConversions(RHS.get());
12331 if (RHS.isInvalid())
12332 return QualType();
12334 QualType LHSType = LHS.get()->getType();
12335 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
12336 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
12337 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
12338 : LHSType;
12340 // Note that RHS might not be a vector
12341 QualType RHSType = RHS.get()->getType();
12342 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
12343 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
12344 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
12345 : RHSType;
12347 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
12348 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
12349 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12350 << LHSType << RHSType << LHS.get()->getSourceRange();
12351 return QualType();
12354 if (!LHSEleType->isIntegerType()) {
12355 S.Diag(Loc, diag::err_typecheck_expect_int)
12356 << LHS.get()->getType() << LHS.get()->getSourceRange();
12357 return QualType();
12360 if (!RHSEleType->isIntegerType()) {
12361 S.Diag(Loc, diag::err_typecheck_expect_int)
12362 << RHS.get()->getType() << RHS.get()->getSourceRange();
12363 return QualType();
12366 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
12367 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
12368 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
12369 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12370 << LHSType << RHSType << LHS.get()->getSourceRange()
12371 << RHS.get()->getSourceRange();
12372 return QualType();
12375 if (!LHSType->isSveVLSBuiltinType()) {
12376 assert(RHSType->isSveVLSBuiltinType());
12377 if (IsCompAssign)
12378 return RHSType;
12379 if (LHSEleType != RHSEleType) {
12380 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
12381 LHSEleType = RHSEleType;
12383 const llvm::ElementCount VecSize =
12384 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
12385 QualType VecTy =
12386 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
12387 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
12388 LHSType = VecTy;
12389 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
12390 if (S.Context.getTypeSize(RHSBuiltinTy) !=
12391 S.Context.getTypeSize(LHSBuiltinTy)) {
12392 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12393 << LHSType << RHSType << LHS.get()->getSourceRange()
12394 << RHS.get()->getSourceRange();
12395 return QualType();
12397 } else {
12398 const llvm::ElementCount VecSize =
12399 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
12400 if (LHSEleType != RHSEleType) {
12401 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
12402 RHSEleType = LHSEleType;
12404 QualType VecTy =
12405 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
12406 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12409 return LHSType;
12412 // C99 6.5.7
12413 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
12414 SourceLocation Loc, BinaryOperatorKind Opc,
12415 bool IsCompAssign) {
12416 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12418 // Vector shifts promote their scalar inputs to vector type.
12419 if (LHS.get()->getType()->isVectorType() ||
12420 RHS.get()->getType()->isVectorType()) {
12421 if (LangOpts.ZVector) {
12422 // The shift operators for the z vector extensions work basically
12423 // like general shifts, except that neither the LHS nor the RHS is
12424 // allowed to be a "vector bool".
12425 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12426 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12427 return InvalidOperands(Loc, LHS, RHS);
12428 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12429 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12430 return InvalidOperands(Loc, LHS, RHS);
12432 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12435 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12436 RHS.get()->getType()->isSveVLSBuiltinType())
12437 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12439 // Shifts don't perform usual arithmetic conversions, they just do integer
12440 // promotions on each operand. C99 6.5.7p3
12442 // For the LHS, do usual unary conversions, but then reset them away
12443 // if this is a compound assignment.
12444 ExprResult OldLHS = LHS;
12445 LHS = UsualUnaryConversions(LHS.get());
12446 if (LHS.isInvalid())
12447 return QualType();
12448 QualType LHSType = LHS.get()->getType();
12449 if (IsCompAssign) LHS = OldLHS;
12451 // The RHS is simpler.
12452 RHS = UsualUnaryConversions(RHS.get());
12453 if (RHS.isInvalid())
12454 return QualType();
12455 QualType RHSType = RHS.get()->getType();
12457 // C99 6.5.7p2: Each of the operands shall have integer type.
12458 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12459 if ((!LHSType->isFixedPointOrIntegerType() &&
12460 !LHSType->hasIntegerRepresentation()) ||
12461 !RHSType->hasIntegerRepresentation())
12462 return InvalidOperands(Loc, LHS, RHS);
12464 // C++0x: Don't allow scoped enums. FIXME: Use something better than
12465 // hasIntegerRepresentation() above instead of this.
12466 if (isScopedEnumerationType(LHSType) ||
12467 isScopedEnumerationType(RHSType)) {
12468 return InvalidOperands(Loc, LHS, RHS);
12470 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
12472 // "The type of the result is that of the promoted left operand."
12473 return LHSType;
12476 /// Diagnose bad pointer comparisons.
12477 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
12478 ExprResult &LHS, ExprResult &RHS,
12479 bool IsError) {
12480 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12481 : diag::ext_typecheck_comparison_of_distinct_pointers)
12482 << LHS.get()->getType() << RHS.get()->getType()
12483 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12486 /// Returns false if the pointers are converted to a composite type,
12487 /// true otherwise.
12488 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
12489 ExprResult &LHS, ExprResult &RHS) {
12490 // C++ [expr.rel]p2:
12491 // [...] Pointer conversions (4.10) and qualification
12492 // conversions (4.4) are performed on pointer operands (or on
12493 // a pointer operand and a null pointer constant) to bring
12494 // them to their composite pointer type. [...]
12496 // C++ [expr.eq]p1 uses the same notion for (in)equality
12497 // comparisons of pointers.
12499 QualType LHSType = LHS.get()->getType();
12500 QualType RHSType = RHS.get()->getType();
12501 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12502 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12504 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
12505 if (T.isNull()) {
12506 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12507 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12508 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
12509 else
12510 S.InvalidOperands(Loc, LHS, RHS);
12511 return true;
12514 return false;
12517 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
12518 ExprResult &LHS,
12519 ExprResult &RHS,
12520 bool IsError) {
12521 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12522 : diag::ext_typecheck_comparison_of_fptr_to_void)
12523 << LHS.get()->getType() << RHS.get()->getType()
12524 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12527 static bool isObjCObjectLiteral(ExprResult &E) {
12528 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12529 case Stmt::ObjCArrayLiteralClass:
12530 case Stmt::ObjCDictionaryLiteralClass:
12531 case Stmt::ObjCStringLiteralClass:
12532 case Stmt::ObjCBoxedExprClass:
12533 return true;
12534 default:
12535 // Note that ObjCBoolLiteral is NOT an object literal!
12536 return false;
12540 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12541 const ObjCObjectPointerType *Type =
12542 LHS->getType()->getAs<ObjCObjectPointerType>();
12544 // If this is not actually an Objective-C object, bail out.
12545 if (!Type)
12546 return false;
12548 // Get the LHS object's interface type.
12549 QualType InterfaceType = Type->getPointeeType();
12551 // If the RHS isn't an Objective-C object, bail out.
12552 if (!RHS->getType()->isObjCObjectPointerType())
12553 return false;
12555 // Try to find the -isEqual: method.
12556 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
12557 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
12558 InterfaceType,
12559 /*IsInstance=*/true);
12560 if (!Method) {
12561 if (Type->isObjCIdType()) {
12562 // For 'id', just check the global pool.
12563 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
12564 /*receiverId=*/true);
12565 } else {
12566 // Check protocols.
12567 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
12568 /*IsInstance=*/true);
12572 if (!Method)
12573 return false;
12575 QualType T = Method->parameters()[0]->getType();
12576 if (!T->isObjCObjectPointerType())
12577 return false;
12579 QualType R = Method->getReturnType();
12580 if (!R->isScalarType())
12581 return false;
12583 return true;
12586 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
12587 FromE = FromE->IgnoreParenImpCasts();
12588 switch (FromE->getStmtClass()) {
12589 default:
12590 break;
12591 case Stmt::ObjCStringLiteralClass:
12592 // "string literal"
12593 return LK_String;
12594 case Stmt::ObjCArrayLiteralClass:
12595 // "array literal"
12596 return LK_Array;
12597 case Stmt::ObjCDictionaryLiteralClass:
12598 // "dictionary literal"
12599 return LK_Dictionary;
12600 case Stmt::BlockExprClass:
12601 return LK_Block;
12602 case Stmt::ObjCBoxedExprClass: {
12603 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
12604 switch (Inner->getStmtClass()) {
12605 case Stmt::IntegerLiteralClass:
12606 case Stmt::FloatingLiteralClass:
12607 case Stmt::CharacterLiteralClass:
12608 case Stmt::ObjCBoolLiteralExprClass:
12609 case Stmt::CXXBoolLiteralExprClass:
12610 // "numeric literal"
12611 return LK_Numeric;
12612 case Stmt::ImplicitCastExprClass: {
12613 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
12614 // Boolean literals can be represented by implicit casts.
12615 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
12616 return LK_Numeric;
12617 break;
12619 default:
12620 break;
12622 return LK_Boxed;
12625 return LK_None;
12628 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
12629 ExprResult &LHS, ExprResult &RHS,
12630 BinaryOperator::Opcode Opc){
12631 Expr *Literal;
12632 Expr *Other;
12633 if (isObjCObjectLiteral(LHS)) {
12634 Literal = LHS.get();
12635 Other = RHS.get();
12636 } else {
12637 Literal = RHS.get();
12638 Other = LHS.get();
12641 // Don't warn on comparisons against nil.
12642 Other = Other->IgnoreParenCasts();
12643 if (Other->isNullPointerConstant(S.getASTContext(),
12644 Expr::NPC_ValueDependentIsNotNull))
12645 return;
12647 // This should be kept in sync with warn_objc_literal_comparison.
12648 // LK_String should always be after the other literals, since it has its own
12649 // warning flag.
12650 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
12651 assert(LiteralKind != Sema::LK_Block);
12652 if (LiteralKind == Sema::LK_None) {
12653 llvm_unreachable("Unknown Objective-C object literal kind");
12656 if (LiteralKind == Sema::LK_String)
12657 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
12658 << Literal->getSourceRange();
12659 else
12660 S.Diag(Loc, diag::warn_objc_literal_comparison)
12661 << LiteralKind << Literal->getSourceRange();
12663 if (BinaryOperator::isEqualityOp(Opc) &&
12664 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
12665 SourceLocation Start = LHS.get()->getBeginLoc();
12666 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
12667 CharSourceRange OpRange =
12668 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12670 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
12671 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
12672 << FixItHint::CreateReplacement(OpRange, " isEqual:")
12673 << FixItHint::CreateInsertion(End, "]");
12677 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12678 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
12679 ExprResult &RHS, SourceLocation Loc,
12680 BinaryOperatorKind Opc) {
12681 // Check that left hand side is !something.
12682 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
12683 if (!UO || UO->getOpcode() != UO_LNot) return;
12685 // Only check if the right hand side is non-bool arithmetic type.
12686 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12688 // Make sure that the something in !something is not bool.
12689 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12690 if (SubExpr->isKnownToHaveBooleanValue()) return;
12692 // Emit warning.
12693 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12694 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
12695 << Loc << IsBitwiseOp;
12697 // First note suggest !(x < y)
12698 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12699 SourceLocation FirstClose = RHS.get()->getEndLoc();
12700 FirstClose = S.getLocForEndOfToken(FirstClose);
12701 if (FirstClose.isInvalid())
12702 FirstOpen = SourceLocation();
12703 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
12704 << IsBitwiseOp
12705 << FixItHint::CreateInsertion(FirstOpen, "(")
12706 << FixItHint::CreateInsertion(FirstClose, ")");
12708 // Second note suggests (!x) < y
12709 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12710 SourceLocation SecondClose = LHS.get()->getEndLoc();
12711 SecondClose = S.getLocForEndOfToken(SecondClose);
12712 if (SecondClose.isInvalid())
12713 SecondOpen = SourceLocation();
12714 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
12715 << FixItHint::CreateInsertion(SecondOpen, "(")
12716 << FixItHint::CreateInsertion(SecondClose, ")");
12719 // Returns true if E refers to a non-weak array.
12720 static bool checkForArray(const Expr *E) {
12721 const ValueDecl *D = nullptr;
12722 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
12723 D = DR->getDecl();
12724 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
12725 if (Mem->isImplicitAccess())
12726 D = Mem->getMemberDecl();
12728 if (!D)
12729 return false;
12730 return D->getType()->isArrayType() && !D->isWeak();
12733 /// Diagnose some forms of syntactically-obvious tautological comparison.
12734 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
12735 Expr *LHS, Expr *RHS,
12736 BinaryOperatorKind Opc) {
12737 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12738 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12740 QualType LHSType = LHS->getType();
12741 QualType RHSType = RHS->getType();
12742 if (LHSType->hasFloatingRepresentation() ||
12743 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12744 S.inTemplateInstantiation())
12745 return;
12747 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12748 // Tautological diagnostics.
12749 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12750 return;
12752 // Comparisons between two array types are ill-formed for operator<=>, so
12753 // we shouldn't emit any additional warnings about it.
12754 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12755 return;
12757 // For non-floating point types, check for self-comparisons of the form
12758 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12759 // often indicate logic errors in the program.
12761 // NOTE: Don't warn about comparison expressions resulting from macro
12762 // expansion. Also don't warn about comparisons which are only self
12763 // comparisons within a template instantiation. The warnings should catch
12764 // obvious cases in the definition of the template anyways. The idea is to
12765 // warn when the typed comparison operator will always evaluate to the same
12766 // result.
12768 // Used for indexing into %select in warn_comparison_always
12769 enum {
12770 AlwaysConstant,
12771 AlwaysTrue,
12772 AlwaysFalse,
12773 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12776 // C++2a [depr.array.comp]:
12777 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12778 // operands of array type are deprecated.
12779 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
12780 RHSStripped->getType()->isArrayType()) {
12781 S.Diag(Loc, diag::warn_depr_array_comparison)
12782 << LHS->getSourceRange() << RHS->getSourceRange()
12783 << LHSStripped->getType() << RHSStripped->getType();
12784 // Carry on to produce the tautological comparison warning, if this
12785 // expression is potentially-evaluated, we can resolve the array to a
12786 // non-weak declaration, and so on.
12789 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12790 if (Expr::isSameComparisonOperand(LHS, RHS)) {
12791 unsigned Result;
12792 switch (Opc) {
12793 case BO_EQ:
12794 case BO_LE:
12795 case BO_GE:
12796 Result = AlwaysTrue;
12797 break;
12798 case BO_NE:
12799 case BO_LT:
12800 case BO_GT:
12801 Result = AlwaysFalse;
12802 break;
12803 case BO_Cmp:
12804 Result = AlwaysEqual;
12805 break;
12806 default:
12807 Result = AlwaysConstant;
12808 break;
12810 S.DiagRuntimeBehavior(Loc, nullptr,
12811 S.PDiag(diag::warn_comparison_always)
12812 << 0 /*self-comparison*/
12813 << Result);
12814 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12815 // What is it always going to evaluate to?
12816 unsigned Result;
12817 switch (Opc) {
12818 case BO_EQ: // e.g. array1 == array2
12819 Result = AlwaysFalse;
12820 break;
12821 case BO_NE: // e.g. array1 != array2
12822 Result = AlwaysTrue;
12823 break;
12824 default: // e.g. array1 <= array2
12825 // The best we can say is 'a constant'
12826 Result = AlwaysConstant;
12827 break;
12829 S.DiagRuntimeBehavior(Loc, nullptr,
12830 S.PDiag(diag::warn_comparison_always)
12831 << 1 /*array comparison*/
12832 << Result);
12836 if (isa<CastExpr>(LHSStripped))
12837 LHSStripped = LHSStripped->IgnoreParenCasts();
12838 if (isa<CastExpr>(RHSStripped))
12839 RHSStripped = RHSStripped->IgnoreParenCasts();
12841 // Warn about comparisons against a string constant (unless the other
12842 // operand is null); the user probably wants string comparison function.
12843 Expr *LiteralString = nullptr;
12844 Expr *LiteralStringStripped = nullptr;
12845 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12846 !RHSStripped->isNullPointerConstant(S.Context,
12847 Expr::NPC_ValueDependentIsNull)) {
12848 LiteralString = LHS;
12849 LiteralStringStripped = LHSStripped;
12850 } else if ((isa<StringLiteral>(RHSStripped) ||
12851 isa<ObjCEncodeExpr>(RHSStripped)) &&
12852 !LHSStripped->isNullPointerConstant(S.Context,
12853 Expr::NPC_ValueDependentIsNull)) {
12854 LiteralString = RHS;
12855 LiteralStringStripped = RHSStripped;
12858 if (LiteralString) {
12859 S.DiagRuntimeBehavior(Loc, nullptr,
12860 S.PDiag(diag::warn_stringcompare)
12861 << isa<ObjCEncodeExpr>(LiteralStringStripped)
12862 << LiteralString->getSourceRange());
12866 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
12867 switch (CK) {
12868 default: {
12869 #ifndef NDEBUG
12870 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12871 << "\n";
12872 #endif
12873 llvm_unreachable("unhandled cast kind");
12875 case CK_UserDefinedConversion:
12876 return ICK_Identity;
12877 case CK_LValueToRValue:
12878 return ICK_Lvalue_To_Rvalue;
12879 case CK_ArrayToPointerDecay:
12880 return ICK_Array_To_Pointer;
12881 case CK_FunctionToPointerDecay:
12882 return ICK_Function_To_Pointer;
12883 case CK_IntegralCast:
12884 return ICK_Integral_Conversion;
12885 case CK_FloatingCast:
12886 return ICK_Floating_Conversion;
12887 case CK_IntegralToFloating:
12888 case CK_FloatingToIntegral:
12889 return ICK_Floating_Integral;
12890 case CK_IntegralComplexCast:
12891 case CK_FloatingComplexCast:
12892 case CK_FloatingComplexToIntegralComplex:
12893 case CK_IntegralComplexToFloatingComplex:
12894 return ICK_Complex_Conversion;
12895 case CK_FloatingComplexToReal:
12896 case CK_FloatingRealToComplex:
12897 case CK_IntegralComplexToReal:
12898 case CK_IntegralRealToComplex:
12899 return ICK_Complex_Real;
12903 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12904 QualType FromType,
12905 SourceLocation Loc) {
12906 // Check for a narrowing implicit conversion.
12907 StandardConversionSequence SCS;
12908 SCS.setAsIdentityConversion();
12909 SCS.setToType(0, FromType);
12910 SCS.setToType(1, ToType);
12911 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12912 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12914 APValue PreNarrowingValue;
12915 QualType PreNarrowingType;
12916 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12917 PreNarrowingType,
12918 /*IgnoreFloatToIntegralConversion*/ true)) {
12919 case NK_Dependent_Narrowing:
12920 // Implicit conversion to a narrower type, but the expression is
12921 // value-dependent so we can't tell whether it's actually narrowing.
12922 case NK_Not_Narrowing:
12923 return false;
12925 case NK_Constant_Narrowing:
12926 // Implicit conversion to a narrower type, and the value is not a constant
12927 // expression.
12928 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12929 << /*Constant*/ 1
12930 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12931 return true;
12933 case NK_Variable_Narrowing:
12934 // Implicit conversion to a narrower type, and the value is not a constant
12935 // expression.
12936 case NK_Type_Narrowing:
12937 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12938 << /*Constant*/ 0 << FromType << ToType;
12939 // TODO: It's not a constant expression, but what if the user intended it
12940 // to be? Can we produce notes to help them figure out why it isn't?
12941 return true;
12943 llvm_unreachable("unhandled case in switch");
12946 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
12947 ExprResult &LHS,
12948 ExprResult &RHS,
12949 SourceLocation Loc) {
12950 QualType LHSType = LHS.get()->getType();
12951 QualType RHSType = RHS.get()->getType();
12952 // Dig out the original argument type and expression before implicit casts
12953 // were applied. These are the types/expressions we need to check the
12954 // [expr.spaceship] requirements against.
12955 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12956 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12957 QualType LHSStrippedType = LHSStripped.get()->getType();
12958 QualType RHSStrippedType = RHSStripped.get()->getType();
12960 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12961 // other is not, the program is ill-formed.
12962 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12963 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12964 return QualType();
12967 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12968 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12969 RHSStrippedType->isEnumeralType();
12970 if (NumEnumArgs == 1) {
12971 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12972 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12973 if (OtherTy->hasFloatingRepresentation()) {
12974 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12975 return QualType();
12978 if (NumEnumArgs == 2) {
12979 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12980 // type E, the operator yields the result of converting the operands
12981 // to the underlying type of E and applying <=> to the converted operands.
12982 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12983 S.InvalidOperands(Loc, LHS, RHS);
12984 return QualType();
12986 QualType IntType =
12987 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
12988 assert(IntType->isArithmeticType());
12990 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12991 // promote the boolean type, and all other promotable integer types, to
12992 // avoid this.
12993 if (S.Context.isPromotableIntegerType(IntType))
12994 IntType = S.Context.getPromotedIntegerType(IntType);
12996 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12997 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12998 LHSType = RHSType = IntType;
13001 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
13002 // usual arithmetic conversions are applied to the operands.
13003 QualType Type =
13004 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
13005 if (LHS.isInvalid() || RHS.isInvalid())
13006 return QualType();
13007 if (Type.isNull())
13008 return S.InvalidOperands(Loc, LHS, RHS);
13010 std::optional<ComparisonCategoryType> CCT =
13011 getComparisonCategoryForBuiltinCmp(Type);
13012 if (!CCT)
13013 return S.InvalidOperands(Loc, LHS, RHS);
13015 bool HasNarrowing = checkThreeWayNarrowingConversion(
13016 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
13017 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
13018 RHS.get()->getBeginLoc());
13019 if (HasNarrowing)
13020 return QualType();
13022 assert(!Type.isNull() && "composite type for <=> has not been set");
13024 return S.CheckComparisonCategoryType(
13025 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
13028 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
13029 ExprResult &RHS,
13030 SourceLocation Loc,
13031 BinaryOperatorKind Opc) {
13032 if (Opc == BO_Cmp)
13033 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
13035 // C99 6.5.8p3 / C99 6.5.9p4
13036 QualType Type =
13037 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
13038 if (LHS.isInvalid() || RHS.isInvalid())
13039 return QualType();
13040 if (Type.isNull())
13041 return S.InvalidOperands(Loc, LHS, RHS);
13042 assert(Type->isArithmeticType() || Type->isEnumeralType());
13044 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
13045 return S.InvalidOperands(Loc, LHS, RHS);
13047 // Check for comparisons of floating point operands using != and ==.
13048 if (Type->hasFloatingRepresentation())
13049 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13051 // The result of comparisons is 'bool' in C++, 'int' in C.
13052 return S.Context.getLogicalOperationType();
13055 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
13056 if (!NullE.get()->getType()->isAnyPointerType())
13057 return;
13058 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
13059 if (!E.get()->getType()->isAnyPointerType() &&
13060 E.get()->isNullPointerConstant(Context,
13061 Expr::NPC_ValueDependentIsNotNull) ==
13062 Expr::NPCK_ZeroExpression) {
13063 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
13064 if (CL->getValue() == 0)
13065 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
13066 << NullValue
13067 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
13068 NullValue ? "NULL" : "(void *)0");
13069 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
13070 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
13071 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
13072 if (T == Context.CharTy)
13073 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
13074 << NullValue
13075 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
13076 NullValue ? "NULL" : "(void *)0");
13081 // C99 6.5.8, C++ [expr.rel]
13082 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
13083 SourceLocation Loc,
13084 BinaryOperatorKind Opc) {
13085 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
13086 bool IsThreeWay = Opc == BO_Cmp;
13087 bool IsOrdered = IsRelational || IsThreeWay;
13088 auto IsAnyPointerType = [](ExprResult E) {
13089 QualType Ty = E.get()->getType();
13090 return Ty->isPointerType() || Ty->isMemberPointerType();
13093 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
13094 // type, array-to-pointer, ..., conversions are performed on both operands to
13095 // bring them to their composite type.
13096 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
13097 // any type-related checks.
13098 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
13099 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13100 if (LHS.isInvalid())
13101 return QualType();
13102 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13103 if (RHS.isInvalid())
13104 return QualType();
13105 } else {
13106 LHS = DefaultLvalueConversion(LHS.get());
13107 if (LHS.isInvalid())
13108 return QualType();
13109 RHS = DefaultLvalueConversion(RHS.get());
13110 if (RHS.isInvalid())
13111 return QualType();
13114 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
13115 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
13116 CheckPtrComparisonWithNullChar(LHS, RHS);
13117 CheckPtrComparisonWithNullChar(RHS, LHS);
13120 // Handle vector comparisons separately.
13121 if (LHS.get()->getType()->isVectorType() ||
13122 RHS.get()->getType()->isVectorType())
13123 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
13125 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13126 RHS.get()->getType()->isSveVLSBuiltinType())
13127 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
13129 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13130 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13132 QualType LHSType = LHS.get()->getType();
13133 QualType RHSType = RHS.get()->getType();
13134 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
13135 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
13136 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
13138 if ((LHSType->isPointerType() &&
13139 LHSType->getPointeeType().isWebAssemblyReferenceType()) ||
13140 (RHSType->isPointerType() &&
13141 RHSType->getPointeeType().isWebAssemblyReferenceType()))
13142 return InvalidOperands(Loc, LHS, RHS);
13144 const Expr::NullPointerConstantKind LHSNullKind =
13145 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
13146 const Expr::NullPointerConstantKind RHSNullKind =
13147 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
13148 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
13149 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
13151 auto computeResultTy = [&]() {
13152 if (Opc != BO_Cmp)
13153 return Context.getLogicalOperationType();
13154 assert(getLangOpts().CPlusPlus);
13155 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
13157 QualType CompositeTy = LHS.get()->getType();
13158 assert(!CompositeTy->isReferenceType());
13160 std::optional<ComparisonCategoryType> CCT =
13161 getComparisonCategoryForBuiltinCmp(CompositeTy);
13162 if (!CCT)
13163 return InvalidOperands(Loc, LHS, RHS);
13165 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
13166 // P0946R0: Comparisons between a null pointer constant and an object
13167 // pointer result in std::strong_equality, which is ill-formed under
13168 // P1959R0.
13169 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
13170 << (LHSIsNull ? LHS.get()->getSourceRange()
13171 : RHS.get()->getSourceRange());
13172 return QualType();
13175 return CheckComparisonCategoryType(
13176 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
13179 if (!IsOrdered && LHSIsNull != RHSIsNull) {
13180 bool IsEquality = Opc == BO_EQ;
13181 if (RHSIsNull)
13182 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
13183 RHS.get()->getSourceRange());
13184 else
13185 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
13186 LHS.get()->getSourceRange());
13189 if (IsOrdered && LHSType->isFunctionPointerType() &&
13190 RHSType->isFunctionPointerType()) {
13191 // Valid unless a relational comparison of function pointers
13192 bool IsError = Opc == BO_Cmp;
13193 auto DiagID =
13194 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
13195 : getLangOpts().CPlusPlus
13196 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
13197 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
13198 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
13199 << RHS.get()->getSourceRange();
13200 if (IsError)
13201 return QualType();
13204 if ((LHSType->isIntegerType() && !LHSIsNull) ||
13205 (RHSType->isIntegerType() && !RHSIsNull)) {
13206 // Skip normal pointer conversion checks in this case; we have better
13207 // diagnostics for this below.
13208 } else if (getLangOpts().CPlusPlus) {
13209 // Equality comparison of a function pointer to a void pointer is invalid,
13210 // but we allow it as an extension.
13211 // FIXME: If we really want to allow this, should it be part of composite
13212 // pointer type computation so it works in conditionals too?
13213 if (!IsOrdered &&
13214 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
13215 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
13216 // This is a gcc extension compatibility comparison.
13217 // In a SFINAE context, we treat this as a hard error to maintain
13218 // conformance with the C++ standard.
13219 diagnoseFunctionPointerToVoidComparison(
13220 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
13222 if (isSFINAEContext())
13223 return QualType();
13225 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13226 return computeResultTy();
13229 // C++ [expr.eq]p2:
13230 // If at least one operand is a pointer [...] bring them to their
13231 // composite pointer type.
13232 // C++ [expr.spaceship]p6
13233 // If at least one of the operands is of pointer type, [...] bring them
13234 // to their composite pointer type.
13235 // C++ [expr.rel]p2:
13236 // If both operands are pointers, [...] bring them to their composite
13237 // pointer type.
13238 // For <=>, the only valid non-pointer types are arrays and functions, and
13239 // we already decayed those, so this is really the same as the relational
13240 // comparison rule.
13241 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
13242 (IsOrdered ? 2 : 1) &&
13243 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
13244 RHSType->isObjCObjectPointerType()))) {
13245 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13246 return QualType();
13247 return computeResultTy();
13249 } else if (LHSType->isPointerType() &&
13250 RHSType->isPointerType()) { // C99 6.5.8p2
13251 // All of the following pointer-related warnings are GCC extensions, except
13252 // when handling null pointer constants.
13253 QualType LCanPointeeTy =
13254 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
13255 QualType RCanPointeeTy =
13256 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
13258 // C99 6.5.9p2 and C99 6.5.8p2
13259 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
13260 RCanPointeeTy.getUnqualifiedType())) {
13261 if (IsRelational) {
13262 // Pointers both need to point to complete or incomplete types
13263 if ((LCanPointeeTy->isIncompleteType() !=
13264 RCanPointeeTy->isIncompleteType()) &&
13265 !getLangOpts().C11) {
13266 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
13267 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
13268 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
13269 << RCanPointeeTy->isIncompleteType();
13272 } else if (!IsRelational &&
13273 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
13274 // Valid unless comparison between non-null pointer and function pointer
13275 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
13276 && !LHSIsNull && !RHSIsNull)
13277 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
13278 /*isError*/false);
13279 } else {
13280 // Invalid
13281 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
13283 if (LCanPointeeTy != RCanPointeeTy) {
13284 // Treat NULL constant as a special case in OpenCL.
13285 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
13286 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
13287 Diag(Loc,
13288 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
13289 << LHSType << RHSType << 0 /* comparison */
13290 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
13293 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
13294 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
13295 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
13296 : CK_BitCast;
13297 if (LHSIsNull && !RHSIsNull)
13298 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
13299 else
13300 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
13302 return computeResultTy();
13306 // C++ [expr.eq]p4:
13307 // Two operands of type std::nullptr_t or one operand of type
13308 // std::nullptr_t and the other a null pointer constant compare
13309 // equal.
13310 // C23 6.5.9p5:
13311 // If both operands have type nullptr_t or one operand has type nullptr_t
13312 // and the other is a null pointer constant, they compare equal if the
13313 // former is a null pointer.
13314 if (!IsOrdered && LHSIsNull && RHSIsNull) {
13315 if (LHSType->isNullPtrType()) {
13316 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13317 return computeResultTy();
13319 if (RHSType->isNullPtrType()) {
13320 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13321 return computeResultTy();
13325 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
13326 // C23 6.5.9p6:
13327 // Otherwise, at least one operand is a pointer. If one is a pointer and
13328 // the other is a null pointer constant or has type nullptr_t, they
13329 // compare equal
13330 if (LHSIsNull && RHSType->isPointerType()) {
13331 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13332 return computeResultTy();
13334 if (RHSIsNull && LHSType->isPointerType()) {
13335 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13336 return computeResultTy();
13340 // Comparison of Objective-C pointers and block pointers against nullptr_t.
13341 // These aren't covered by the composite pointer type rules.
13342 if (!IsOrdered && RHSType->isNullPtrType() &&
13343 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
13344 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13345 return computeResultTy();
13347 if (!IsOrdered && LHSType->isNullPtrType() &&
13348 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
13349 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13350 return computeResultTy();
13353 if (getLangOpts().CPlusPlus) {
13354 if (IsRelational &&
13355 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
13356 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
13357 // HACK: Relational comparison of nullptr_t against a pointer type is
13358 // invalid per DR583, but we allow it within std::less<> and friends,
13359 // since otherwise common uses of it break.
13360 // FIXME: Consider removing this hack once LWG fixes std::less<> and
13361 // friends to have std::nullptr_t overload candidates.
13362 DeclContext *DC = CurContext;
13363 if (isa<FunctionDecl>(DC))
13364 DC = DC->getParent();
13365 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
13366 if (CTSD->isInStdNamespace() &&
13367 llvm::StringSwitch<bool>(CTSD->getName())
13368 .Cases("less", "less_equal", "greater", "greater_equal", true)
13369 .Default(false)) {
13370 if (RHSType->isNullPtrType())
13371 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13372 else
13373 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13374 return computeResultTy();
13379 // C++ [expr.eq]p2:
13380 // If at least one operand is a pointer to member, [...] bring them to
13381 // their composite pointer type.
13382 if (!IsOrdered &&
13383 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
13384 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13385 return QualType();
13386 else
13387 return computeResultTy();
13391 // Handle block pointer types.
13392 if (!IsOrdered && LHSType->isBlockPointerType() &&
13393 RHSType->isBlockPointerType()) {
13394 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
13395 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
13397 if (!LHSIsNull && !RHSIsNull &&
13398 !Context.typesAreCompatible(lpointee, rpointee)) {
13399 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13400 << LHSType << RHSType << LHS.get()->getSourceRange()
13401 << RHS.get()->getSourceRange();
13403 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13404 return computeResultTy();
13407 // Allow block pointers to be compared with null pointer constants.
13408 if (!IsOrdered
13409 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
13410 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
13411 if (!LHSIsNull && !RHSIsNull) {
13412 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
13413 ->getPointeeType()->isVoidType())
13414 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
13415 ->getPointeeType()->isVoidType())))
13416 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13417 << LHSType << RHSType << LHS.get()->getSourceRange()
13418 << RHS.get()->getSourceRange();
13420 if (LHSIsNull && !RHSIsNull)
13421 LHS = ImpCastExprToType(LHS.get(), RHSType,
13422 RHSType->isPointerType() ? CK_BitCast
13423 : CK_AnyPointerToBlockPointerCast);
13424 else
13425 RHS = ImpCastExprToType(RHS.get(), LHSType,
13426 LHSType->isPointerType() ? CK_BitCast
13427 : CK_AnyPointerToBlockPointerCast);
13428 return computeResultTy();
13431 if (LHSType->isObjCObjectPointerType() ||
13432 RHSType->isObjCObjectPointerType()) {
13433 const PointerType *LPT = LHSType->getAs<PointerType>();
13434 const PointerType *RPT = RHSType->getAs<PointerType>();
13435 if (LPT || RPT) {
13436 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13437 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13439 if (!LPtrToVoid && !RPtrToVoid &&
13440 !Context.typesAreCompatible(LHSType, RHSType)) {
13441 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13442 /*isError*/false);
13444 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13445 // the RHS, but we have test coverage for this behavior.
13446 // FIXME: Consider using convertPointersToCompositeType in C++.
13447 if (LHSIsNull && !RHSIsNull) {
13448 Expr *E = LHS.get();
13449 if (getLangOpts().ObjCAutoRefCount)
13450 CheckObjCConversion(SourceRange(), RHSType, E,
13451 CCK_ImplicitConversion);
13452 LHS = ImpCastExprToType(E, RHSType,
13453 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13455 else {
13456 Expr *E = RHS.get();
13457 if (getLangOpts().ObjCAutoRefCount)
13458 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
13459 /*Diagnose=*/true,
13460 /*DiagnoseCFAudited=*/false, Opc);
13461 RHS = ImpCastExprToType(E, LHSType,
13462 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13464 return computeResultTy();
13466 if (LHSType->isObjCObjectPointerType() &&
13467 RHSType->isObjCObjectPointerType()) {
13468 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
13469 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13470 /*isError*/false);
13471 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
13472 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
13474 if (LHSIsNull && !RHSIsNull)
13475 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
13476 else
13477 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13478 return computeResultTy();
13481 if (!IsOrdered && LHSType->isBlockPointerType() &&
13482 RHSType->isBlockCompatibleObjCPointerType(Context)) {
13483 LHS = ImpCastExprToType(LHS.get(), RHSType,
13484 CK_BlockPointerToObjCPointerCast);
13485 return computeResultTy();
13486 } else if (!IsOrdered &&
13487 LHSType->isBlockCompatibleObjCPointerType(Context) &&
13488 RHSType->isBlockPointerType()) {
13489 RHS = ImpCastExprToType(RHS.get(), LHSType,
13490 CK_BlockPointerToObjCPointerCast);
13491 return computeResultTy();
13494 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13495 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13496 unsigned DiagID = 0;
13497 bool isError = false;
13498 if (LangOpts.DebuggerSupport) {
13499 // Under a debugger, allow the comparison of pointers to integers,
13500 // since users tend to want to compare addresses.
13501 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13502 (RHSIsNull && RHSType->isIntegerType())) {
13503 if (IsOrdered) {
13504 isError = getLangOpts().CPlusPlus;
13505 DiagID =
13506 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13507 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13509 } else if (getLangOpts().CPlusPlus) {
13510 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13511 isError = true;
13512 } else if (IsOrdered)
13513 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13514 else
13515 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13517 if (DiagID) {
13518 Diag(Loc, DiagID)
13519 << LHSType << RHSType << LHS.get()->getSourceRange()
13520 << RHS.get()->getSourceRange();
13521 if (isError)
13522 return QualType();
13525 if (LHSType->isIntegerType())
13526 LHS = ImpCastExprToType(LHS.get(), RHSType,
13527 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13528 else
13529 RHS = ImpCastExprToType(RHS.get(), LHSType,
13530 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13531 return computeResultTy();
13534 // Handle block pointers.
13535 if (!IsOrdered && RHSIsNull
13536 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13537 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13538 return computeResultTy();
13540 if (!IsOrdered && LHSIsNull
13541 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13542 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13543 return computeResultTy();
13546 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13547 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13548 return computeResultTy();
13551 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13552 return computeResultTy();
13555 if (LHSIsNull && RHSType->isQueueT()) {
13556 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13557 return computeResultTy();
13560 if (LHSType->isQueueT() && RHSIsNull) {
13561 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13562 return computeResultTy();
13566 return InvalidOperands(Loc, LHS, RHS);
13569 // Return a signed ext_vector_type that is of identical size and number of
13570 // elements. For floating point vectors, return an integer type of identical
13571 // size and number of elements. In the non ext_vector_type case, search from
13572 // the largest type to the smallest type to avoid cases where long long == long,
13573 // where long gets picked over long long.
13574 QualType Sema::GetSignedVectorType(QualType V) {
13575 const VectorType *VTy = V->castAs<VectorType>();
13576 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
13578 if (isa<ExtVectorType>(VTy)) {
13579 if (VTy->isExtVectorBoolType())
13580 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
13581 if (TypeSize == Context.getTypeSize(Context.CharTy))
13582 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
13583 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13584 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
13585 if (TypeSize == Context.getTypeSize(Context.IntTy))
13586 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
13587 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13588 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
13589 if (TypeSize == Context.getTypeSize(Context.LongTy))
13590 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
13591 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13592 "Unhandled vector element size in vector compare");
13593 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
13596 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13597 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
13598 VectorKind::Generic);
13599 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13600 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
13601 VectorKind::Generic);
13602 if (TypeSize == Context.getTypeSize(Context.LongTy))
13603 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
13604 VectorKind::Generic);
13605 if (TypeSize == Context.getTypeSize(Context.IntTy))
13606 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
13607 VectorKind::Generic);
13608 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13609 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
13610 VectorKind::Generic);
13611 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13612 "Unhandled vector element size in vector compare");
13613 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
13614 VectorKind::Generic);
13617 QualType Sema::GetSignedSizelessVectorType(QualType V) {
13618 const BuiltinType *VTy = V->castAs<BuiltinType>();
13619 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13621 const QualType ETy = V->getSveEltType(Context);
13622 const auto TypeSize = Context.getTypeSize(ETy);
13624 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
13625 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
13626 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
13629 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
13630 /// operates on extended vector types. Instead of producing an IntTy result,
13631 /// like a scalar comparison, a vector comparison produces a vector of integer
13632 /// types.
13633 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
13634 SourceLocation Loc,
13635 BinaryOperatorKind Opc) {
13636 if (Opc == BO_Cmp) {
13637 Diag(Loc, diag::err_three_way_vector_comparison);
13638 return QualType();
13641 // Check to make sure we're operating on vectors of the same type and width,
13642 // Allowing one side to be a scalar of element type.
13643 QualType vType =
13644 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
13645 /*AllowBothBool*/ true,
13646 /*AllowBoolConversions*/ getLangOpts().ZVector,
13647 /*AllowBooleanOperation*/ true,
13648 /*ReportInvalid*/ true);
13649 if (vType.isNull())
13650 return vType;
13652 QualType LHSType = LHS.get()->getType();
13654 // Determine the return type of a vector compare. By default clang will return
13655 // a scalar for all vector compares except vector bool and vector pixel.
13656 // With the gcc compiler we will always return a vector type and with the xl
13657 // compiler we will always return a scalar type. This switch allows choosing
13658 // which behavior is prefered.
13659 if (getLangOpts().AltiVec) {
13660 switch (getLangOpts().getAltivecSrcCompat()) {
13661 case LangOptions::AltivecSrcCompatKind::Mixed:
13662 // If AltiVec, the comparison results in a numeric type, i.e.
13663 // bool for C++, int for C
13664 if (vType->castAs<VectorType>()->getVectorKind() ==
13665 VectorKind::AltiVecVector)
13666 return Context.getLogicalOperationType();
13667 else
13668 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
13669 break;
13670 case LangOptions::AltivecSrcCompatKind::GCC:
13671 // For GCC we always return the vector type.
13672 break;
13673 case LangOptions::AltivecSrcCompatKind::XL:
13674 return Context.getLogicalOperationType();
13675 break;
13679 // For non-floating point types, check for self-comparisons of the form
13680 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13681 // often indicate logic errors in the program.
13682 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13684 // Check for comparisons of floating point operands using != and ==.
13685 if (LHSType->hasFloatingRepresentation()) {
13686 assert(RHS.get()->getType()->hasFloatingRepresentation());
13687 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13690 // Return a signed type for the vector.
13691 return GetSignedVectorType(vType);
13694 QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
13695 ExprResult &RHS,
13696 SourceLocation Loc,
13697 BinaryOperatorKind Opc) {
13698 if (Opc == BO_Cmp) {
13699 Diag(Loc, diag::err_three_way_vector_comparison);
13700 return QualType();
13703 // Check to make sure we're operating on vectors of the same type and width,
13704 // Allowing one side to be a scalar of element type.
13705 QualType vType = CheckSizelessVectorOperands(
13706 LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
13708 if (vType.isNull())
13709 return vType;
13711 QualType LHSType = LHS.get()->getType();
13713 // For non-floating point types, check for self-comparisons of the form
13714 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13715 // often indicate logic errors in the program.
13716 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13718 // Check for comparisons of floating point operands using != and ==.
13719 if (LHSType->hasFloatingRepresentation()) {
13720 assert(RHS.get()->getType()->hasFloatingRepresentation());
13721 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13724 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13725 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13727 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13728 RHSBuiltinTy->isSVEBool())
13729 return LHSType;
13731 // Return a signed type for the vector.
13732 return GetSignedSizelessVectorType(vType);
13735 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13736 const ExprResult &XorRHS,
13737 const SourceLocation Loc) {
13738 // Do not diagnose macros.
13739 if (Loc.isMacroID())
13740 return;
13742 // Do not diagnose if both LHS and RHS are macros.
13743 if (XorLHS.get()->getExprLoc().isMacroID() &&
13744 XorRHS.get()->getExprLoc().isMacroID())
13745 return;
13747 bool Negative = false;
13748 bool ExplicitPlus = false;
13749 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
13750 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
13752 if (!LHSInt)
13753 return;
13754 if (!RHSInt) {
13755 // Check negative literals.
13756 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
13757 UnaryOperatorKind Opc = UO->getOpcode();
13758 if (Opc != UO_Minus && Opc != UO_Plus)
13759 return;
13760 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
13761 if (!RHSInt)
13762 return;
13763 Negative = (Opc == UO_Minus);
13764 ExplicitPlus = !Negative;
13765 } else {
13766 return;
13770 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13771 llvm::APInt RightSideValue = RHSInt->getValue();
13772 if (LeftSideValue != 2 && LeftSideValue != 10)
13773 return;
13775 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13776 return;
13778 CharSourceRange ExprRange = CharSourceRange::getCharRange(
13779 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
13780 llvm::StringRef ExprStr =
13781 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
13783 CharSourceRange XorRange =
13784 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
13785 llvm::StringRef XorStr =
13786 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
13787 // Do not diagnose if xor keyword/macro is used.
13788 if (XorStr == "xor")
13789 return;
13791 std::string LHSStr = std::string(Lexer::getSourceText(
13792 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13793 S.getSourceManager(), S.getLangOpts()));
13794 std::string RHSStr = std::string(Lexer::getSourceText(
13795 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13796 S.getSourceManager(), S.getLangOpts()));
13798 if (Negative) {
13799 RightSideValue = -RightSideValue;
13800 RHSStr = "-" + RHSStr;
13801 } else if (ExplicitPlus) {
13802 RHSStr = "+" + RHSStr;
13805 StringRef LHSStrRef = LHSStr;
13806 StringRef RHSStrRef = RHSStr;
13807 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13808 // literals.
13809 if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
13810 RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
13811 LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
13812 RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
13813 (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
13814 (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
13815 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13816 return;
13818 bool SuggestXor =
13819 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13820 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13821 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13822 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13823 std::string SuggestedExpr = "1 << " + RHSStr;
13824 bool Overflow = false;
13825 llvm::APInt One = (LeftSideValue - 1);
13826 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13827 if (Overflow) {
13828 if (RightSideIntValue < 64)
13829 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13830 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13831 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13832 else if (RightSideIntValue == 64)
13833 S.Diag(Loc, diag::warn_xor_used_as_pow)
13834 << ExprStr << toString(XorValue, 10, true);
13835 else
13836 return;
13837 } else {
13838 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13839 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13840 << toString(PowValue, 10, true)
13841 << FixItHint::CreateReplacement(
13842 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13845 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13846 << ("0x2 ^ " + RHSStr) << SuggestXor;
13847 } else if (LeftSideValue == 10) {
13848 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13849 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13850 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13851 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13852 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13853 << ("0xA ^ " + RHSStr) << SuggestXor;
13857 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13858 SourceLocation Loc) {
13859 // Ensure that either both operands are of the same vector type, or
13860 // one operand is of a vector type and the other is of its element type.
13861 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13862 /*AllowBothBool*/ true,
13863 /*AllowBoolConversions*/ false,
13864 /*AllowBooleanOperation*/ false,
13865 /*ReportInvalid*/ false);
13866 if (vType.isNull())
13867 return InvalidOperands(Loc, LHS, RHS);
13868 if (getLangOpts().OpenCL &&
13869 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13870 vType->hasFloatingRepresentation())
13871 return InvalidOperands(Loc, LHS, RHS);
13872 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13873 // usage of the logical operators && and || with vectors in C. This
13874 // check could be notionally dropped.
13875 if (!getLangOpts().CPlusPlus &&
13876 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13877 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13879 return GetSignedVectorType(LHS.get()->getType());
13882 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
13883 SourceLocation Loc,
13884 bool IsCompAssign) {
13885 if (!IsCompAssign) {
13886 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13887 if (LHS.isInvalid())
13888 return QualType();
13890 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13891 if (RHS.isInvalid())
13892 return QualType();
13894 // For conversion purposes, we ignore any qualifiers.
13895 // For example, "const float" and "float" are equivalent.
13896 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13897 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13899 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13900 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13901 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13903 if (Context.hasSameType(LHSType, RHSType))
13904 return Context.getCommonSugaredType(LHSType, RHSType);
13906 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13907 // case we have to return InvalidOperands.
13908 ExprResult OriginalLHS = LHS;
13909 ExprResult OriginalRHS = RHS;
13910 if (LHSMatType && !RHSMatType) {
13911 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13912 if (!RHS.isInvalid())
13913 return LHSType;
13915 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13918 if (!LHSMatType && RHSMatType) {
13919 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13920 if (!LHS.isInvalid())
13921 return RHSType;
13922 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13925 return InvalidOperands(Loc, LHS, RHS);
13928 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
13929 SourceLocation Loc,
13930 bool IsCompAssign) {
13931 if (!IsCompAssign) {
13932 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13933 if (LHS.isInvalid())
13934 return QualType();
13936 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13937 if (RHS.isInvalid())
13938 return QualType();
13940 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13941 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13942 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13944 if (LHSMatType && RHSMatType) {
13945 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13946 return InvalidOperands(Loc, LHS, RHS);
13948 if (Context.hasSameType(LHSMatType, RHSMatType))
13949 return Context.getCommonSugaredType(
13950 LHS.get()->getType().getUnqualifiedType(),
13951 RHS.get()->getType().getUnqualifiedType());
13953 QualType LHSELTy = LHSMatType->getElementType(),
13954 RHSELTy = RHSMatType->getElementType();
13955 if (!Context.hasSameType(LHSELTy, RHSELTy))
13956 return InvalidOperands(Loc, LHS, RHS);
13958 return Context.getConstantMatrixType(
13959 Context.getCommonSugaredType(LHSELTy, RHSELTy),
13960 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13962 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13965 static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
13966 switch (Opc) {
13967 default:
13968 return false;
13969 case BO_And:
13970 case BO_AndAssign:
13971 case BO_Or:
13972 case BO_OrAssign:
13973 case BO_Xor:
13974 case BO_XorAssign:
13975 return true;
13979 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
13980 SourceLocation Loc,
13981 BinaryOperatorKind Opc) {
13982 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13984 bool IsCompAssign =
13985 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13987 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13989 if (LHS.get()->getType()->isVectorType() ||
13990 RHS.get()->getType()->isVectorType()) {
13991 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13992 RHS.get()->getType()->hasIntegerRepresentation())
13993 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13994 /*AllowBothBool*/ true,
13995 /*AllowBoolConversions*/ getLangOpts().ZVector,
13996 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13997 /*ReportInvalid*/ true);
13998 return InvalidOperands(Loc, LHS, RHS);
14001 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
14002 RHS.get()->getType()->isSveVLSBuiltinType()) {
14003 if (LHS.get()->getType()->hasIntegerRepresentation() &&
14004 RHS.get()->getType()->hasIntegerRepresentation())
14005 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
14006 ACK_BitwiseOp);
14007 return InvalidOperands(Loc, LHS, RHS);
14010 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
14011 RHS.get()->getType()->isSveVLSBuiltinType()) {
14012 if (LHS.get()->getType()->hasIntegerRepresentation() &&
14013 RHS.get()->getType()->hasIntegerRepresentation())
14014 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
14015 ACK_BitwiseOp);
14016 return InvalidOperands(Loc, LHS, RHS);
14019 if (Opc == BO_And)
14020 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
14022 if (LHS.get()->getType()->hasFloatingRepresentation() ||
14023 RHS.get()->getType()->hasFloatingRepresentation())
14024 return InvalidOperands(Loc, LHS, RHS);
14026 ExprResult LHSResult = LHS, RHSResult = RHS;
14027 QualType compType = UsualArithmeticConversions(
14028 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
14029 if (LHSResult.isInvalid() || RHSResult.isInvalid())
14030 return QualType();
14031 LHS = LHSResult.get();
14032 RHS = RHSResult.get();
14034 if (Opc == BO_Xor)
14035 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
14037 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
14038 return compType;
14039 return InvalidOperands(Loc, LHS, RHS);
14042 // C99 6.5.[13,14]
14043 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
14044 SourceLocation Loc,
14045 BinaryOperatorKind Opc) {
14046 // Check vector operands differently.
14047 if (LHS.get()->getType()->isVectorType() ||
14048 RHS.get()->getType()->isVectorType())
14049 return CheckVectorLogicalOperands(LHS, RHS, Loc);
14051 bool EnumConstantInBoolContext = false;
14052 for (const ExprResult &HS : {LHS, RHS}) {
14053 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
14054 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
14055 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
14056 EnumConstantInBoolContext = true;
14060 if (EnumConstantInBoolContext)
14061 Diag(Loc, diag::warn_enum_constant_in_bool_context);
14063 // WebAssembly tables can't be used with logical operators.
14064 QualType LHSTy = LHS.get()->getType();
14065 QualType RHSTy = RHS.get()->getType();
14066 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
14067 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
14068 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
14069 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
14070 return InvalidOperands(Loc, LHS, RHS);
14073 // Diagnose cases where the user write a logical and/or but probably meant a
14074 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
14075 // is a constant.
14076 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
14077 !LHS.get()->getType()->isBooleanType() &&
14078 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
14079 // Don't warn in macros or template instantiations.
14080 !Loc.isMacroID() && !inTemplateInstantiation()) {
14081 // If the RHS can be constant folded, and if it constant folds to something
14082 // that isn't 0 or 1 (which indicate a potential logical operation that
14083 // happened to fold to true/false) then warn.
14084 // Parens on the RHS are ignored.
14085 Expr::EvalResult EVResult;
14086 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
14087 llvm::APSInt Result = EVResult.Val.getInt();
14088 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
14089 !RHS.get()->getExprLoc().isMacroID()) ||
14090 (Result != 0 && Result != 1)) {
14091 Diag(Loc, diag::warn_logical_instead_of_bitwise)
14092 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
14093 // Suggest replacing the logical operator with the bitwise version
14094 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
14095 << (Opc == BO_LAnd ? "&" : "|")
14096 << FixItHint::CreateReplacement(
14097 SourceRange(Loc, getLocForEndOfToken(Loc)),
14098 Opc == BO_LAnd ? "&" : "|");
14099 if (Opc == BO_LAnd)
14100 // Suggest replacing "Foo() && kNonZero" with "Foo()"
14101 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
14102 << FixItHint::CreateRemoval(
14103 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
14104 RHS.get()->getEndLoc()));
14109 if (!Context.getLangOpts().CPlusPlus) {
14110 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
14111 // not operate on the built-in scalar and vector float types.
14112 if (Context.getLangOpts().OpenCL &&
14113 Context.getLangOpts().OpenCLVersion < 120) {
14114 if (LHS.get()->getType()->isFloatingType() ||
14115 RHS.get()->getType()->isFloatingType())
14116 return InvalidOperands(Loc, LHS, RHS);
14119 LHS = UsualUnaryConversions(LHS.get());
14120 if (LHS.isInvalid())
14121 return QualType();
14123 RHS = UsualUnaryConversions(RHS.get());
14124 if (RHS.isInvalid())
14125 return QualType();
14127 if (!LHS.get()->getType()->isScalarType() ||
14128 !RHS.get()->getType()->isScalarType())
14129 return InvalidOperands(Loc, LHS, RHS);
14131 return Context.IntTy;
14134 // The following is safe because we only use this method for
14135 // non-overloadable operands.
14137 // C++ [expr.log.and]p1
14138 // C++ [expr.log.or]p1
14139 // The operands are both contextually converted to type bool.
14140 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
14141 if (LHSRes.isInvalid())
14142 return InvalidOperands(Loc, LHS, RHS);
14143 LHS = LHSRes;
14145 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
14146 if (RHSRes.isInvalid())
14147 return InvalidOperands(Loc, LHS, RHS);
14148 RHS = RHSRes;
14150 // C++ [expr.log.and]p2
14151 // C++ [expr.log.or]p2
14152 // The result is a bool.
14153 return Context.BoolTy;
14156 static bool IsReadonlyMessage(Expr *E, Sema &S) {
14157 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14158 if (!ME) return false;
14159 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
14160 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
14161 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
14162 if (!Base) return false;
14163 return Base->getMethodDecl() != nullptr;
14166 /// Is the given expression (which must be 'const') a reference to a
14167 /// variable which was originally non-const, but which has become
14168 /// 'const' due to being captured within a block?
14169 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
14170 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
14171 assert(E->isLValue() && E->getType().isConstQualified());
14172 E = E->IgnoreParens();
14174 // Must be a reference to a declaration from an enclosing scope.
14175 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14176 if (!DRE) return NCCK_None;
14177 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
14179 // The declaration must be a variable which is not declared 'const'.
14180 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
14181 if (!var) return NCCK_None;
14182 if (var->getType().isConstQualified()) return NCCK_None;
14183 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
14185 // Decide whether the first capture was for a block or a lambda.
14186 DeclContext *DC = S.CurContext, *Prev = nullptr;
14187 // Decide whether the first capture was for a block or a lambda.
14188 while (DC) {
14189 // For init-capture, it is possible that the variable belongs to the
14190 // template pattern of the current context.
14191 if (auto *FD = dyn_cast<FunctionDecl>(DC))
14192 if (var->isInitCapture() &&
14193 FD->getTemplateInstantiationPattern() == var->getDeclContext())
14194 break;
14195 if (DC == var->getDeclContext())
14196 break;
14197 Prev = DC;
14198 DC = DC->getParent();
14200 // Unless we have an init-capture, we've gone one step too far.
14201 if (!var->isInitCapture())
14202 DC = Prev;
14203 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
14206 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
14207 Ty = Ty.getNonReferenceType();
14208 if (IsDereference && Ty->isPointerType())
14209 Ty = Ty->getPointeeType();
14210 return !Ty.isConstQualified();
14213 // Update err_typecheck_assign_const and note_typecheck_assign_const
14214 // when this enum is changed.
14215 enum {
14216 ConstFunction,
14217 ConstVariable,
14218 ConstMember,
14219 ConstMethod,
14220 NestedConstMember,
14221 ConstUnknown, // Keep as last element
14224 /// Emit the "read-only variable not assignable" error and print notes to give
14225 /// more information about why the variable is not assignable, such as pointing
14226 /// to the declaration of a const variable, showing that a method is const, or
14227 /// that the function is returning a const reference.
14228 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
14229 SourceLocation Loc) {
14230 SourceRange ExprRange = E->getSourceRange();
14232 // Only emit one error on the first const found. All other consts will emit
14233 // a note to the error.
14234 bool DiagnosticEmitted = false;
14236 // Track if the current expression is the result of a dereference, and if the
14237 // next checked expression is the result of a dereference.
14238 bool IsDereference = false;
14239 bool NextIsDereference = false;
14241 // Loop to process MemberExpr chains.
14242 while (true) {
14243 IsDereference = NextIsDereference;
14245 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
14246 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14247 NextIsDereference = ME->isArrow();
14248 const ValueDecl *VD = ME->getMemberDecl();
14249 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
14250 // Mutable fields can be modified even if the class is const.
14251 if (Field->isMutable()) {
14252 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
14253 break;
14256 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
14257 if (!DiagnosticEmitted) {
14258 S.Diag(Loc, diag::err_typecheck_assign_const)
14259 << ExprRange << ConstMember << false /*static*/ << Field
14260 << Field->getType();
14261 DiagnosticEmitted = true;
14263 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14264 << ConstMember << false /*static*/ << Field << Field->getType()
14265 << Field->getSourceRange();
14267 E = ME->getBase();
14268 continue;
14269 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
14270 if (VDecl->getType().isConstQualified()) {
14271 if (!DiagnosticEmitted) {
14272 S.Diag(Loc, diag::err_typecheck_assign_const)
14273 << ExprRange << ConstMember << true /*static*/ << VDecl
14274 << VDecl->getType();
14275 DiagnosticEmitted = true;
14277 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14278 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
14279 << VDecl->getSourceRange();
14281 // Static fields do not inherit constness from parents.
14282 break;
14284 break; // End MemberExpr
14285 } else if (const ArraySubscriptExpr *ASE =
14286 dyn_cast<ArraySubscriptExpr>(E)) {
14287 E = ASE->getBase()->IgnoreParenImpCasts();
14288 continue;
14289 } else if (const ExtVectorElementExpr *EVE =
14290 dyn_cast<ExtVectorElementExpr>(E)) {
14291 E = EVE->getBase()->IgnoreParenImpCasts();
14292 continue;
14294 break;
14297 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
14298 // Function calls
14299 const FunctionDecl *FD = CE->getDirectCallee();
14300 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
14301 if (!DiagnosticEmitted) {
14302 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
14303 << ConstFunction << FD;
14304 DiagnosticEmitted = true;
14306 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
14307 diag::note_typecheck_assign_const)
14308 << ConstFunction << FD << FD->getReturnType()
14309 << FD->getReturnTypeSourceRange();
14311 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14312 // Point to variable declaration.
14313 if (const ValueDecl *VD = DRE->getDecl()) {
14314 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
14315 if (!DiagnosticEmitted) {
14316 S.Diag(Loc, diag::err_typecheck_assign_const)
14317 << ExprRange << ConstVariable << VD << VD->getType();
14318 DiagnosticEmitted = true;
14320 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14321 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
14324 } else if (isa<CXXThisExpr>(E)) {
14325 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
14326 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
14327 if (MD->isConst()) {
14328 if (!DiagnosticEmitted) {
14329 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
14330 << ConstMethod << MD;
14331 DiagnosticEmitted = true;
14333 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
14334 << ConstMethod << MD << MD->getSourceRange();
14340 if (DiagnosticEmitted)
14341 return;
14343 // Can't determine a more specific message, so display the generic error.
14344 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
14347 enum OriginalExprKind {
14348 OEK_Variable,
14349 OEK_Member,
14350 OEK_LValue
14353 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
14354 const RecordType *Ty,
14355 SourceLocation Loc, SourceRange Range,
14356 OriginalExprKind OEK,
14357 bool &DiagnosticEmitted) {
14358 std::vector<const RecordType *> RecordTypeList;
14359 RecordTypeList.push_back(Ty);
14360 unsigned NextToCheckIndex = 0;
14361 // We walk the record hierarchy breadth-first to ensure that we print
14362 // diagnostics in field nesting order.
14363 while (RecordTypeList.size() > NextToCheckIndex) {
14364 bool IsNested = NextToCheckIndex > 0;
14365 for (const FieldDecl *Field :
14366 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
14367 // First, check every field for constness.
14368 QualType FieldTy = Field->getType();
14369 if (FieldTy.isConstQualified()) {
14370 if (!DiagnosticEmitted) {
14371 S.Diag(Loc, diag::err_typecheck_assign_const)
14372 << Range << NestedConstMember << OEK << VD
14373 << IsNested << Field;
14374 DiagnosticEmitted = true;
14376 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
14377 << NestedConstMember << IsNested << Field
14378 << FieldTy << Field->getSourceRange();
14381 // Then we append it to the list to check next in order.
14382 FieldTy = FieldTy.getCanonicalType();
14383 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
14384 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
14385 RecordTypeList.push_back(FieldRecTy);
14388 ++NextToCheckIndex;
14392 /// Emit an error for the case where a record we are trying to assign to has a
14393 /// const-qualified field somewhere in its hierarchy.
14394 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14395 SourceLocation Loc) {
14396 QualType Ty = E->getType();
14397 assert(Ty->isRecordType() && "lvalue was not record?");
14398 SourceRange Range = E->getSourceRange();
14399 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
14400 bool DiagEmitted = false;
14402 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
14403 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
14404 Range, OEK_Member, DiagEmitted);
14405 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14406 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
14407 Range, OEK_Variable, DiagEmitted);
14408 else
14409 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
14410 Range, OEK_LValue, DiagEmitted);
14411 if (!DiagEmitted)
14412 DiagnoseConstAssignment(S, E, Loc);
14415 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14416 /// emit an error and return true. If so, return false.
14417 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
14418 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14420 S.CheckShadowingDeclModification(E, Loc);
14422 SourceLocation OrigLoc = Loc;
14423 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
14424 &Loc);
14425 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14426 IsLV = Expr::MLV_InvalidMessageExpression;
14427 if (IsLV == Expr::MLV_Valid)
14428 return false;
14430 unsigned DiagID = 0;
14431 bool NeedType = false;
14432 switch (IsLV) { // C99 6.5.16p2
14433 case Expr::MLV_ConstQualified:
14434 // Use a specialized diagnostic when we're assigning to an object
14435 // from an enclosing function or block.
14436 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
14437 if (NCCK == NCCK_Block)
14438 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14439 else
14440 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14441 break;
14444 // In ARC, use some specialized diagnostics for occasions where we
14445 // infer 'const'. These are always pseudo-strong variables.
14446 if (S.getLangOpts().ObjCAutoRefCount) {
14447 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
14448 if (declRef && isa<VarDecl>(declRef->getDecl())) {
14449 VarDecl *var = cast<VarDecl>(declRef->getDecl());
14451 // Use the normal diagnostic if it's pseudo-__strong but the
14452 // user actually wrote 'const'.
14453 if (var->isARCPseudoStrong() &&
14454 (!var->getTypeSourceInfo() ||
14455 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14456 // There are three pseudo-strong cases:
14457 // - self
14458 ObjCMethodDecl *method = S.getCurMethodDecl();
14459 if (method && var == method->getSelfDecl()) {
14460 DiagID = method->isClassMethod()
14461 ? diag::err_typecheck_arc_assign_self_class_method
14462 : diag::err_typecheck_arc_assign_self;
14464 // - Objective-C externally_retained attribute.
14465 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14466 isa<ParmVarDecl>(var)) {
14467 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14469 // - fast enumeration variables
14470 } else {
14471 DiagID = diag::err_typecheck_arr_assign_enumeration;
14474 SourceRange Assign;
14475 if (Loc != OrigLoc)
14476 Assign = SourceRange(OrigLoc, OrigLoc);
14477 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14478 // We need to preserve the AST regardless, so migration tool
14479 // can do its job.
14480 return false;
14485 // If none of the special cases above are triggered, then this is a
14486 // simple const assignment.
14487 if (DiagID == 0) {
14488 DiagnoseConstAssignment(S, E, Loc);
14489 return true;
14492 break;
14493 case Expr::MLV_ConstAddrSpace:
14494 DiagnoseConstAssignment(S, E, Loc);
14495 return true;
14496 case Expr::MLV_ConstQualifiedField:
14497 DiagnoseRecursiveConstFields(S, E, Loc);
14498 return true;
14499 case Expr::MLV_ArrayType:
14500 case Expr::MLV_ArrayTemporary:
14501 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14502 NeedType = true;
14503 break;
14504 case Expr::MLV_NotObjectType:
14505 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14506 NeedType = true;
14507 break;
14508 case Expr::MLV_LValueCast:
14509 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14510 break;
14511 case Expr::MLV_Valid:
14512 llvm_unreachable("did not take early return for MLV_Valid");
14513 case Expr::MLV_InvalidExpression:
14514 case Expr::MLV_MemberFunction:
14515 case Expr::MLV_ClassTemporary:
14516 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14517 break;
14518 case Expr::MLV_IncompleteType:
14519 case Expr::MLV_IncompleteVoidType:
14520 return S.RequireCompleteType(Loc, E->getType(),
14521 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
14522 case Expr::MLV_DuplicateVectorComponents:
14523 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14524 break;
14525 case Expr::MLV_NoSetterProperty:
14526 llvm_unreachable("readonly properties should be processed differently");
14527 case Expr::MLV_InvalidMessageExpression:
14528 DiagID = diag::err_readonly_message_assignment;
14529 break;
14530 case Expr::MLV_SubObjCPropertySetting:
14531 DiagID = diag::err_no_subobject_property_setting;
14532 break;
14535 SourceRange Assign;
14536 if (Loc != OrigLoc)
14537 Assign = SourceRange(OrigLoc, OrigLoc);
14538 if (NeedType)
14539 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14540 else
14541 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14542 return true;
14545 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14546 SourceLocation Loc,
14547 Sema &Sema) {
14548 if (Sema.inTemplateInstantiation())
14549 return;
14550 if (Sema.isUnevaluatedContext())
14551 return;
14552 if (Loc.isInvalid() || Loc.isMacroID())
14553 return;
14554 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14555 return;
14557 // C / C++ fields
14558 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
14559 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
14560 if (ML && MR) {
14561 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
14562 return;
14563 const ValueDecl *LHSDecl =
14564 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
14565 const ValueDecl *RHSDecl =
14566 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
14567 if (LHSDecl != RHSDecl)
14568 return;
14569 if (LHSDecl->getType().isVolatileQualified())
14570 return;
14571 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14572 if (RefTy->getPointeeType().isVolatileQualified())
14573 return;
14575 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
14578 // Objective-C instance variables
14579 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
14580 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
14581 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14582 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
14583 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
14584 if (RL && RR && RL->getDecl() == RR->getDecl())
14585 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
14589 // C99 6.5.16.1
14590 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
14591 SourceLocation Loc,
14592 QualType CompoundType,
14593 BinaryOperatorKind Opc) {
14594 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14596 // Verify that LHS is a modifiable lvalue, and emit error if not.
14597 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
14598 return QualType();
14600 QualType LHSType = LHSExpr->getType();
14601 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14602 CompoundType;
14603 // OpenCL v1.2 s6.1.1.1 p2:
14604 // The half data type can only be used to declare a pointer to a buffer that
14605 // contains half values
14606 if (getLangOpts().OpenCL &&
14607 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
14608 LHSType->isHalfType()) {
14609 Diag(Loc, diag::err_opencl_half_load_store) << 1
14610 << LHSType.getUnqualifiedType();
14611 return QualType();
14614 // WebAssembly tables can't be used on RHS of an assignment expression.
14615 if (RHSType->isWebAssemblyTableType()) {
14616 Diag(Loc, diag::err_wasm_table_art) << 0;
14617 return QualType();
14620 AssignConvertType ConvTy;
14621 if (CompoundType.isNull()) {
14622 Expr *RHSCheck = RHS.get();
14624 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
14626 QualType LHSTy(LHSType);
14627 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
14628 if (RHS.isInvalid())
14629 return QualType();
14630 // Special case of NSObject attributes on c-style pointer types.
14631 if (ConvTy == IncompatiblePointer &&
14632 ((Context.isObjCNSObjectType(LHSType) &&
14633 RHSType->isObjCObjectPointerType()) ||
14634 (Context.isObjCNSObjectType(RHSType) &&
14635 LHSType->isObjCObjectPointerType())))
14636 ConvTy = Compatible;
14638 if (ConvTy == Compatible &&
14639 LHSType->isObjCObjectType())
14640 Diag(Loc, diag::err_objc_object_assignment)
14641 << LHSType;
14643 // If the RHS is a unary plus or minus, check to see if they = and + are
14644 // right next to each other. If so, the user may have typo'd "x =+ 4"
14645 // instead of "x += 4".
14646 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
14647 RHSCheck = ICE->getSubExpr();
14648 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
14649 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14650 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14651 // Only if the two operators are exactly adjacent.
14652 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
14653 // And there is a space or other character before the subexpr of the
14654 // unary +/-. We don't want to warn on "x=-1".
14655 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
14656 UO->getSubExpr()->getBeginLoc().isFileID()) {
14657 Diag(Loc, diag::warn_not_compound_assign)
14658 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14659 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14663 if (ConvTy == Compatible) {
14664 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14665 // Warn about retain cycles where a block captures the LHS, but
14666 // not if the LHS is a simple variable into which the block is
14667 // being stored...unless that variable can be captured by reference!
14668 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14669 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
14670 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14671 checkRetainCycles(LHSExpr, RHS.get());
14674 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14675 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
14676 // It is safe to assign a weak reference into a strong variable.
14677 // Although this code can still have problems:
14678 // id x = self.weakProp;
14679 // id y = self.weakProp;
14680 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14681 // paths through the function. This should be revisited if
14682 // -Wrepeated-use-of-weak is made flow-sensitive.
14683 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14684 // variable, which will be valid for the current autorelease scope.
14685 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14686 RHS.get()->getBeginLoc()))
14687 getCurFunction()->markSafeWeakUse(RHS.get());
14689 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14690 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
14693 } else {
14694 // Compound assignment "x += y"
14695 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14698 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
14699 RHS.get(), AA_Assigning))
14700 return QualType();
14702 CheckForNullPointerDereference(*this, LHSExpr);
14704 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14705 if (CompoundType.isNull()) {
14706 // C++2a [expr.ass]p5:
14707 // A simple-assignment whose left operand is of a volatile-qualified
14708 // type is deprecated unless the assignment is either a discarded-value
14709 // expression or an unevaluated operand
14710 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
14714 // C11 6.5.16p3: The type of an assignment expression is the type of the
14715 // left operand would have after lvalue conversion.
14716 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14717 // qualified type, the value has the unqualified version of the type of the
14718 // lvalue; additionally, if the lvalue has atomic type, the value has the
14719 // non-atomic version of the type of the lvalue.
14720 // C++ 5.17p1: the type of the assignment expression is that of its left
14721 // operand.
14722 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14725 // Scenarios to ignore if expression E is:
14726 // 1. an explicit cast expression into void
14727 // 2. a function call expression that returns void
14728 static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14729 E = E->IgnoreParens();
14731 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
14732 if (CE->getCastKind() == CK_ToVoid) {
14733 return true;
14736 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14737 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14738 CE->getSubExpr()->getType()->isDependentType()) {
14739 return true;
14743 if (const auto *CE = dyn_cast<CallExpr>(E))
14744 return CE->getCallReturnType(Context)->isVoidType();
14745 return false;
14748 // Look for instances where it is likely the comma operator is confused with
14749 // another operator. There is an explicit list of acceptable expressions for
14750 // the left hand side of the comma operator, otherwise emit a warning.
14751 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
14752 // No warnings in macros
14753 if (Loc.isMacroID())
14754 return;
14756 // Don't warn in template instantiations.
14757 if (inTemplateInstantiation())
14758 return;
14760 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14761 // instead, skip more than needed, then call back into here with the
14762 // CommaVisitor in SemaStmt.cpp.
14763 // The listed locations are the initialization and increment portions
14764 // of a for loop. The additional checks are on the condition of
14765 // if statements, do/while loops, and for loops.
14766 // Differences in scope flags for C89 mode requires the extra logic.
14767 const unsigned ForIncrementFlags =
14768 getLangOpts().C99 || getLangOpts().CPlusPlus
14769 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
14770 : Scope::ContinueScope | Scope::BreakScope;
14771 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
14772 const unsigned ScopeFlags = getCurScope()->getFlags();
14773 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
14774 (ScopeFlags & ForInitFlags) == ForInitFlags)
14775 return;
14777 // If there are multiple comma operators used together, get the RHS of the
14778 // of the comma operator as the LHS.
14779 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
14780 if (BO->getOpcode() != BO_Comma)
14781 break;
14782 LHS = BO->getRHS();
14785 // Only allow some expressions on LHS to not warn.
14786 if (IgnoreCommaOperand(LHS, Context))
14787 return;
14789 Diag(Loc, diag::warn_comma_operator);
14790 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14791 << LHS->getSourceRange()
14792 << FixItHint::CreateInsertion(LHS->getBeginLoc(),
14793 LangOpts.CPlusPlus ? "static_cast<void>("
14794 : "(void)(")
14795 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
14796 ")");
14799 // C99 6.5.17
14800 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
14801 SourceLocation Loc) {
14802 LHS = S.CheckPlaceholderExpr(LHS.get());
14803 RHS = S.CheckPlaceholderExpr(RHS.get());
14804 if (LHS.isInvalid() || RHS.isInvalid())
14805 return QualType();
14807 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14808 // operands, but not unary promotions.
14809 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14811 // So we treat the LHS as a ignored value, and in C++ we allow the
14812 // containing site to determine what should be done with the RHS.
14813 LHS = S.IgnoredValueConversions(LHS.get());
14814 if (LHS.isInvalid())
14815 return QualType();
14817 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14819 if (!S.getLangOpts().CPlusPlus) {
14820 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
14821 if (RHS.isInvalid())
14822 return QualType();
14823 if (!RHS.get()->getType()->isVoidType())
14824 S.RequireCompleteType(Loc, RHS.get()->getType(),
14825 diag::err_incomplete_type);
14828 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14829 S.DiagnoseCommaOperator(LHS.get(), Loc);
14831 return RHS.get()->getType();
14834 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14835 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14836 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
14837 ExprValueKind &VK,
14838 ExprObjectKind &OK,
14839 SourceLocation OpLoc,
14840 bool IsInc, bool IsPrefix) {
14841 if (Op->isTypeDependent())
14842 return S.Context.DependentTy;
14844 QualType ResType = Op->getType();
14845 // Atomic types can be used for increment / decrement where the non-atomic
14846 // versions can, so ignore the _Atomic() specifier for the purpose of
14847 // checking.
14848 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14849 ResType = ResAtomicType->getValueType();
14851 assert(!ResType.isNull() && "no type for increment/decrement expression");
14853 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14854 // Decrement of bool is not allowed.
14855 if (!IsInc) {
14856 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14857 return QualType();
14859 // Increment of bool sets it to true, but is deprecated.
14860 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14861 : diag::warn_increment_bool)
14862 << Op->getSourceRange();
14863 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14864 // Error on enum increments and decrements in C++ mode
14865 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14866 return QualType();
14867 } else if (ResType->isRealType()) {
14868 // OK!
14869 } else if (ResType->isPointerType()) {
14870 // C99 6.5.2.4p2, 6.5.6p2
14871 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14872 return QualType();
14873 } else if (ResType->isObjCObjectPointerType()) {
14874 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14875 // Otherwise, we just need a complete type.
14876 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14877 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14878 return QualType();
14879 } else if (ResType->isAnyComplexType()) {
14880 // C99 does not support ++/-- on complex types, we allow as an extension.
14881 S.Diag(OpLoc, diag::ext_integer_increment_complex)
14882 << ResType << Op->getSourceRange();
14883 } else if (ResType->isPlaceholderType()) {
14884 ExprResult PR = S.CheckPlaceholderExpr(Op);
14885 if (PR.isInvalid()) return QualType();
14886 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14887 IsInc, IsPrefix);
14888 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14889 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14890 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14891 (ResType->castAs<VectorType>()->getVectorKind() !=
14892 VectorKind::AltiVecBool)) {
14893 // The z vector extensions allow ++ and -- for non-bool vectors.
14894 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14895 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14896 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14897 } else {
14898 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14899 << ResType << int(IsInc) << Op->getSourceRange();
14900 return QualType();
14902 // At this point, we know we have a real, complex or pointer type.
14903 // Now make sure the operand is a modifiable lvalue.
14904 if (CheckForModifiableLvalue(Op, OpLoc, S))
14905 return QualType();
14906 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14907 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14908 // An operand with volatile-qualified type is deprecated
14909 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14910 << IsInc << ResType;
14912 // In C++, a prefix increment is the same type as the operand. Otherwise
14913 // (in C or with postfix), the increment is the unqualified type of the
14914 // operand.
14915 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14916 VK = VK_LValue;
14917 OK = Op->getObjectKind();
14918 return ResType;
14919 } else {
14920 VK = VK_PRValue;
14921 return ResType.getUnqualifiedType();
14926 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14927 /// This routine allows us to typecheck complex/recursive expressions
14928 /// where the declaration is needed for type checking. We only need to
14929 /// handle cases when the expression references a function designator
14930 /// or is an lvalue. Here are some examples:
14931 /// - &(x) => x
14932 /// - &*****f => f for f a function designator.
14933 /// - &s.xx => s
14934 /// - &s.zz[1].yy -> s, if zz is an array
14935 /// - *(x + 1) -> x, if x is an array
14936 /// - &"123"[2] -> 0
14937 /// - & __real__ x -> x
14939 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14940 /// members.
14941 static ValueDecl *getPrimaryDecl(Expr *E) {
14942 switch (E->getStmtClass()) {
14943 case Stmt::DeclRefExprClass:
14944 return cast<DeclRefExpr>(E)->getDecl();
14945 case Stmt::MemberExprClass:
14946 // If this is an arrow operator, the address is an offset from
14947 // the base's value, so the object the base refers to is
14948 // irrelevant.
14949 if (cast<MemberExpr>(E)->isArrow())
14950 return nullptr;
14951 // Otherwise, the expression refers to a part of the base
14952 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14953 case Stmt::ArraySubscriptExprClass: {
14954 // FIXME: This code shouldn't be necessary! We should catch the implicit
14955 // promotion of register arrays earlier.
14956 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14957 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14958 if (ICE->getSubExpr()->getType()->isArrayType())
14959 return getPrimaryDecl(ICE->getSubExpr());
14961 return nullptr;
14963 case Stmt::UnaryOperatorClass: {
14964 UnaryOperator *UO = cast<UnaryOperator>(E);
14966 switch(UO->getOpcode()) {
14967 case UO_Real:
14968 case UO_Imag:
14969 case UO_Extension:
14970 return getPrimaryDecl(UO->getSubExpr());
14971 default:
14972 return nullptr;
14975 case Stmt::ParenExprClass:
14976 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14977 case Stmt::ImplicitCastExprClass:
14978 // If the result of an implicit cast is an l-value, we care about
14979 // the sub-expression; otherwise, the result here doesn't matter.
14980 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14981 case Stmt::CXXUuidofExprClass:
14982 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14983 default:
14984 return nullptr;
14988 namespace {
14989 enum {
14990 AO_Bit_Field = 0,
14991 AO_Vector_Element = 1,
14992 AO_Property_Expansion = 2,
14993 AO_Register_Variable = 3,
14994 AO_Matrix_Element = 4,
14995 AO_No_Error = 5
14998 /// Diagnose invalid operand for address of operations.
15000 /// \param Type The type of operand which cannot have its address taken.
15001 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
15002 Expr *E, unsigned Type) {
15003 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
15006 bool Sema::CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
15007 const Expr *Op,
15008 const CXXMethodDecl *MD) {
15009 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
15011 if (Op != DRE)
15012 return Diag(OpLoc, diag::err_parens_pointer_member_function)
15013 << Op->getSourceRange();
15015 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
15016 if (isa<CXXDestructorDecl>(MD))
15017 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
15018 << DRE->getSourceRange();
15020 if (DRE->getQualifier())
15021 return false;
15023 if (MD->getParent()->getName().empty())
15024 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
15025 << DRE->getSourceRange();
15027 SmallString<32> Str;
15028 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
15029 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
15030 << DRE->getSourceRange()
15031 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
15034 /// CheckAddressOfOperand - The operand of & must be either a function
15035 /// designator or an lvalue designating an object. If it is an lvalue, the
15036 /// object cannot be declared with storage class register or be a bit field.
15037 /// Note: The usual conversions are *not* applied to the operand of the &
15038 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
15039 /// In C++, the operand might be an overloaded function name, in which case
15040 /// we allow the '&' but retain the overloaded-function type.
15041 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
15042 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
15043 if (PTy->getKind() == BuiltinType::Overload) {
15044 Expr *E = OrigOp.get()->IgnoreParens();
15045 if (!isa<OverloadExpr>(E)) {
15046 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
15047 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
15048 << OrigOp.get()->getSourceRange();
15049 return QualType();
15052 OverloadExpr *Ovl = cast<OverloadExpr>(E);
15053 if (isa<UnresolvedMemberExpr>(Ovl))
15054 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
15055 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
15056 << OrigOp.get()->getSourceRange();
15057 return QualType();
15060 return Context.OverloadTy;
15063 if (PTy->getKind() == BuiltinType::UnknownAny)
15064 return Context.UnknownAnyTy;
15066 if (PTy->getKind() == BuiltinType::BoundMember) {
15067 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
15068 << OrigOp.get()->getSourceRange();
15069 return QualType();
15072 OrigOp = CheckPlaceholderExpr(OrigOp.get());
15073 if (OrigOp.isInvalid()) return QualType();
15076 if (OrigOp.get()->isTypeDependent())
15077 return Context.DependentTy;
15079 assert(!OrigOp.get()->hasPlaceholderType());
15081 // Make sure to ignore parentheses in subsequent checks
15082 Expr *op = OrigOp.get()->IgnoreParens();
15084 // In OpenCL captures for blocks called as lambda functions
15085 // are located in the private address space. Blocks used in
15086 // enqueue_kernel can be located in a different address space
15087 // depending on a vendor implementation. Thus preventing
15088 // taking an address of the capture to avoid invalid AS casts.
15089 if (LangOpts.OpenCL) {
15090 auto* VarRef = dyn_cast<DeclRefExpr>(op);
15091 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
15092 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
15093 return QualType();
15097 if (getLangOpts().C99) {
15098 // Implement C99-only parts of addressof rules.
15099 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
15100 if (uOp->getOpcode() == UO_Deref)
15101 // Per C99 6.5.3.2, the address of a deref always returns a valid result
15102 // (assuming the deref expression is valid).
15103 return uOp->getSubExpr()->getType();
15105 // Technically, there should be a check for array subscript
15106 // expressions here, but the result of one is always an lvalue anyway.
15108 ValueDecl *dcl = getPrimaryDecl(op);
15110 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
15111 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
15112 op->getBeginLoc()))
15113 return QualType();
15115 Expr::LValueClassification lval = op->ClassifyLValue(Context);
15116 unsigned AddressOfError = AO_No_Error;
15118 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
15119 bool sfinae = (bool)isSFINAEContext();
15120 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
15121 : diag::ext_typecheck_addrof_temporary)
15122 << op->getType() << op->getSourceRange();
15123 if (sfinae)
15124 return QualType();
15125 // Materialize the temporary as an lvalue so that we can take its address.
15126 OrigOp = op =
15127 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
15128 } else if (isa<ObjCSelectorExpr>(op)) {
15129 return Context.getPointerType(op->getType());
15130 } else if (lval == Expr::LV_MemberFunction) {
15131 // If it's an instance method, make a member pointer.
15132 // The expression must have exactly the form &A::foo.
15134 // If the underlying expression isn't a decl ref, give up.
15135 if (!isa<DeclRefExpr>(op)) {
15136 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
15137 << OrigOp.get()->getSourceRange();
15138 return QualType();
15140 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
15141 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
15143 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
15145 QualType MPTy = Context.getMemberPointerType(
15146 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
15147 // Under the MS ABI, lock down the inheritance model now.
15148 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15149 (void)isCompleteType(OpLoc, MPTy);
15150 return MPTy;
15151 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
15152 // C99 6.5.3.2p1
15153 // The operand must be either an l-value or a function designator
15154 if (!op->getType()->isFunctionType()) {
15155 // Use a special diagnostic for loads from property references.
15156 if (isa<PseudoObjectExpr>(op)) {
15157 AddressOfError = AO_Property_Expansion;
15158 } else {
15159 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
15160 << op->getType() << op->getSourceRange();
15161 return QualType();
15163 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
15164 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
15165 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
15168 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
15169 // The operand cannot be a bit-field
15170 AddressOfError = AO_Bit_Field;
15171 } else if (op->getObjectKind() == OK_VectorComponent) {
15172 // The operand cannot be an element of a vector
15173 AddressOfError = AO_Vector_Element;
15174 } else if (op->getObjectKind() == OK_MatrixComponent) {
15175 // The operand cannot be an element of a matrix.
15176 AddressOfError = AO_Matrix_Element;
15177 } else if (dcl) { // C99 6.5.3.2p1
15178 // We have an lvalue with a decl. Make sure the decl is not declared
15179 // with the register storage-class specifier.
15180 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
15181 // in C++ it is not error to take address of a register
15182 // variable (c++03 7.1.1P3)
15183 if (vd->getStorageClass() == SC_Register &&
15184 !getLangOpts().CPlusPlus) {
15185 AddressOfError = AO_Register_Variable;
15187 } else if (isa<MSPropertyDecl>(dcl)) {
15188 AddressOfError = AO_Property_Expansion;
15189 } else if (isa<FunctionTemplateDecl>(dcl)) {
15190 return Context.OverloadTy;
15191 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
15192 // Okay: we can take the address of a field.
15193 // Could be a pointer to member, though, if there is an explicit
15194 // scope qualifier for the class.
15195 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
15196 DeclContext *Ctx = dcl->getDeclContext();
15197 if (Ctx && Ctx->isRecord()) {
15198 if (dcl->getType()->isReferenceType()) {
15199 Diag(OpLoc,
15200 diag::err_cannot_form_pointer_to_member_of_reference_type)
15201 << dcl->getDeclName() << dcl->getType();
15202 return QualType();
15205 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
15206 Ctx = Ctx->getParent();
15208 QualType MPTy = Context.getMemberPointerType(
15209 op->getType(),
15210 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
15211 // Under the MS ABI, lock down the inheritance model now.
15212 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15213 (void)isCompleteType(OpLoc, MPTy);
15214 return MPTy;
15217 } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl,
15218 MSGuidDecl, UnnamedGlobalConstantDecl>(dcl))
15219 llvm_unreachable("Unknown/unexpected decl type");
15222 if (AddressOfError != AO_No_Error) {
15223 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
15224 return QualType();
15227 if (lval == Expr::LV_IncompleteVoidType) {
15228 // Taking the address of a void variable is technically illegal, but we
15229 // allow it in cases which are otherwise valid.
15230 // Example: "extern void x; void* y = &x;".
15231 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
15234 // If the operand has type "type", the result has type "pointer to type".
15235 if (op->getType()->isObjCObjectType())
15236 return Context.getObjCObjectPointerType(op->getType());
15238 // Cannot take the address of WebAssembly references or tables.
15239 if (Context.getTargetInfo().getTriple().isWasm()) {
15240 QualType OpTy = op->getType();
15241 if (OpTy.isWebAssemblyReferenceType()) {
15242 Diag(OpLoc, diag::err_wasm_ca_reference)
15243 << 1 << OrigOp.get()->getSourceRange();
15244 return QualType();
15246 if (OpTy->isWebAssemblyTableType()) {
15247 Diag(OpLoc, diag::err_wasm_table_pr)
15248 << 1 << OrigOp.get()->getSourceRange();
15249 return QualType();
15253 CheckAddressOfPackedMember(op);
15255 return Context.getPointerType(op->getType());
15258 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
15259 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
15260 if (!DRE)
15261 return;
15262 const Decl *D = DRE->getDecl();
15263 if (!D)
15264 return;
15265 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
15266 if (!Param)
15267 return;
15268 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
15269 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
15270 return;
15271 if (FunctionScopeInfo *FD = S.getCurFunction())
15272 FD->ModifiedNonNullParams.insert(Param);
15275 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
15276 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
15277 SourceLocation OpLoc,
15278 bool IsAfterAmp = false) {
15279 if (Op->isTypeDependent())
15280 return S.Context.DependentTy;
15282 ExprResult ConvResult = S.UsualUnaryConversions(Op);
15283 if (ConvResult.isInvalid())
15284 return QualType();
15285 Op = ConvResult.get();
15286 QualType OpTy = Op->getType();
15287 QualType Result;
15289 if (isa<CXXReinterpretCastExpr>(Op)) {
15290 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
15291 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
15292 Op->getSourceRange());
15295 if (const PointerType *PT = OpTy->getAs<PointerType>())
15297 Result = PT->getPointeeType();
15299 else if (const ObjCObjectPointerType *OPT =
15300 OpTy->getAs<ObjCObjectPointerType>())
15301 Result = OPT->getPointeeType();
15302 else {
15303 ExprResult PR = S.CheckPlaceholderExpr(Op);
15304 if (PR.isInvalid()) return QualType();
15305 if (PR.get() != Op)
15306 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
15309 if (Result.isNull()) {
15310 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
15311 << OpTy << Op->getSourceRange();
15312 return QualType();
15315 if (Result->isVoidType()) {
15316 // C++ [expr.unary.op]p1:
15317 // [...] the expression to which [the unary * operator] is applied shall
15318 // be a pointer to an object type, or a pointer to a function type
15319 LangOptions LO = S.getLangOpts();
15320 if (LO.CPlusPlus)
15321 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
15322 << OpTy << Op->getSourceRange();
15323 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
15324 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
15325 << OpTy << Op->getSourceRange();
15328 // Dereferences are usually l-values...
15329 VK = VK_LValue;
15331 // ...except that certain expressions are never l-values in C.
15332 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
15333 VK = VK_PRValue;
15335 return Result;
15338 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
15339 BinaryOperatorKind Opc;
15340 switch (Kind) {
15341 default: llvm_unreachable("Unknown binop!");
15342 case tok::periodstar: Opc = BO_PtrMemD; break;
15343 case tok::arrowstar: Opc = BO_PtrMemI; break;
15344 case tok::star: Opc = BO_Mul; break;
15345 case tok::slash: Opc = BO_Div; break;
15346 case tok::percent: Opc = BO_Rem; break;
15347 case tok::plus: Opc = BO_Add; break;
15348 case tok::minus: Opc = BO_Sub; break;
15349 case tok::lessless: Opc = BO_Shl; break;
15350 case tok::greatergreater: Opc = BO_Shr; break;
15351 case tok::lessequal: Opc = BO_LE; break;
15352 case tok::less: Opc = BO_LT; break;
15353 case tok::greaterequal: Opc = BO_GE; break;
15354 case tok::greater: Opc = BO_GT; break;
15355 case tok::exclaimequal: Opc = BO_NE; break;
15356 case tok::equalequal: Opc = BO_EQ; break;
15357 case tok::spaceship: Opc = BO_Cmp; break;
15358 case tok::amp: Opc = BO_And; break;
15359 case tok::caret: Opc = BO_Xor; break;
15360 case tok::pipe: Opc = BO_Or; break;
15361 case tok::ampamp: Opc = BO_LAnd; break;
15362 case tok::pipepipe: Opc = BO_LOr; break;
15363 case tok::equal: Opc = BO_Assign; break;
15364 case tok::starequal: Opc = BO_MulAssign; break;
15365 case tok::slashequal: Opc = BO_DivAssign; break;
15366 case tok::percentequal: Opc = BO_RemAssign; break;
15367 case tok::plusequal: Opc = BO_AddAssign; break;
15368 case tok::minusequal: Opc = BO_SubAssign; break;
15369 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15370 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15371 case tok::ampequal: Opc = BO_AndAssign; break;
15372 case tok::caretequal: Opc = BO_XorAssign; break;
15373 case tok::pipeequal: Opc = BO_OrAssign; break;
15374 case tok::comma: Opc = BO_Comma; break;
15376 return Opc;
15379 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
15380 tok::TokenKind Kind) {
15381 UnaryOperatorKind Opc;
15382 switch (Kind) {
15383 default: llvm_unreachable("Unknown unary op!");
15384 case tok::plusplus: Opc = UO_PreInc; break;
15385 case tok::minusminus: Opc = UO_PreDec; break;
15386 case tok::amp: Opc = UO_AddrOf; break;
15387 case tok::star: Opc = UO_Deref; break;
15388 case tok::plus: Opc = UO_Plus; break;
15389 case tok::minus: Opc = UO_Minus; break;
15390 case tok::tilde: Opc = UO_Not; break;
15391 case tok::exclaim: Opc = UO_LNot; break;
15392 case tok::kw___real: Opc = UO_Real; break;
15393 case tok::kw___imag: Opc = UO_Imag; break;
15394 case tok::kw___extension__: Opc = UO_Extension; break;
15396 return Opc;
15399 const FieldDecl *
15400 Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {
15401 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15402 // common for setters.
15403 // struct A {
15404 // int X;
15405 // -void setX(int X) { X = X; }
15406 // +void setX(int X) { this->X = X; }
15407 // };
15409 // Only consider parameters for self assignment fixes.
15410 if (!isa<ParmVarDecl>(SelfAssigned))
15411 return nullptr;
15412 const auto *Method =
15413 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
15414 if (!Method)
15415 return nullptr;
15417 const CXXRecordDecl *Parent = Method->getParent();
15418 // In theory this is fixable if the lambda explicitly captures this, but
15419 // that's added complexity that's rarely going to be used.
15420 if (Parent->isLambda())
15421 return nullptr;
15423 // FIXME: Use an actual Lookup operation instead of just traversing fields
15424 // in order to get base class fields.
15425 auto Field =
15426 llvm::find_if(Parent->fields(),
15427 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15428 return F->getDeclName() == Name;
15430 return (Field != Parent->field_end()) ? *Field : nullptr;
15433 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15434 /// This warning suppressed in the event of macro expansions.
15435 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15436 SourceLocation OpLoc, bool IsBuiltin) {
15437 if (S.inTemplateInstantiation())
15438 return;
15439 if (S.isUnevaluatedContext())
15440 return;
15441 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15442 return;
15443 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15444 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15445 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15446 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15447 if (!LHSDeclRef || !RHSDeclRef ||
15448 LHSDeclRef->getLocation().isMacroID() ||
15449 RHSDeclRef->getLocation().isMacroID())
15450 return;
15451 const ValueDecl *LHSDecl =
15452 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
15453 const ValueDecl *RHSDecl =
15454 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
15455 if (LHSDecl != RHSDecl)
15456 return;
15457 if (LHSDecl->getType().isVolatileQualified())
15458 return;
15459 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15460 if (RefTy->getPointeeType().isVolatileQualified())
15461 return;
15463 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
15464 : diag::warn_self_assignment_overloaded)
15465 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15466 << RHSExpr->getSourceRange();
15467 if (const FieldDecl *SelfAssignField =
15468 S.getSelfAssignmentClassMemberCandidate(RHSDecl))
15469 Diag << 1 << SelfAssignField
15470 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15471 else
15472 Diag << 0;
15475 /// Check if a bitwise-& is performed on an Objective-C pointer. This
15476 /// is usually indicative of introspection within the Objective-C pointer.
15477 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
15478 SourceLocation OpLoc) {
15479 if (!S.getLangOpts().ObjC)
15480 return;
15482 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15483 const Expr *LHS = L.get();
15484 const Expr *RHS = R.get();
15486 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15487 ObjCPointerExpr = LHS;
15488 OtherExpr = RHS;
15490 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15491 ObjCPointerExpr = RHS;
15492 OtherExpr = LHS;
15495 // This warning is deliberately made very specific to reduce false
15496 // positives with logic that uses '&' for hashing. This logic mainly
15497 // looks for code trying to introspect into tagged pointers, which
15498 // code should generally never do.
15499 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
15500 unsigned Diag = diag::warn_objc_pointer_masking;
15501 // Determine if we are introspecting the result of performSelectorXXX.
15502 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15503 // Special case messages to -performSelector and friends, which
15504 // can return non-pointer values boxed in a pointer value.
15505 // Some clients may wish to silence warnings in this subcase.
15506 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
15507 Selector S = ME->getSelector();
15508 StringRef SelArg0 = S.getNameForSlot(0);
15509 if (SelArg0.starts_with("performSelector"))
15510 Diag = diag::warn_objc_pointer_masking_performSelector;
15513 S.Diag(OpLoc, Diag)
15514 << ObjCPointerExpr->getSourceRange();
15518 static NamedDecl *getDeclFromExpr(Expr *E) {
15519 if (!E)
15520 return nullptr;
15521 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
15522 return DRE->getDecl();
15523 if (auto *ME = dyn_cast<MemberExpr>(E))
15524 return ME->getMemberDecl();
15525 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
15526 return IRE->getDecl();
15527 return nullptr;
15530 // This helper function promotes a binary operator's operands (which are of a
15531 // half vector type) to a vector of floats and then truncates the result to
15532 // a vector of either half or short.
15533 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
15534 BinaryOperatorKind Opc, QualType ResultTy,
15535 ExprValueKind VK, ExprObjectKind OK,
15536 bool IsCompAssign, SourceLocation OpLoc,
15537 FPOptionsOverride FPFeatures) {
15538 auto &Context = S.getASTContext();
15539 assert((isVector(ResultTy, Context.HalfTy) ||
15540 isVector(ResultTy, Context.ShortTy)) &&
15541 "Result must be a vector of half or short");
15542 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15543 isVector(RHS.get()->getType(), Context.HalfTy) &&
15544 "both operands expected to be a half vector");
15546 RHS = convertVector(RHS.get(), Context.FloatTy, S);
15547 QualType BinOpResTy = RHS.get()->getType();
15549 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15550 // change BinOpResTy to a vector of ints.
15551 if (isVector(ResultTy, Context.ShortTy))
15552 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
15554 if (IsCompAssign)
15555 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15556 ResultTy, VK, OK, OpLoc, FPFeatures,
15557 BinOpResTy, BinOpResTy);
15559 LHS = convertVector(LHS.get(), Context.FloatTy, S);
15560 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15561 BinOpResTy, VK, OK, OpLoc, FPFeatures);
15562 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15565 static std::pair<ExprResult, ExprResult>
15566 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
15567 Expr *RHSExpr) {
15568 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15569 if (!S.Context.isDependenceAllowed()) {
15570 // C cannot handle TypoExpr nodes on either side of a binop because it
15571 // doesn't handle dependent types properly, so make sure any TypoExprs have
15572 // been dealt with before checking the operands.
15573 LHS = S.CorrectDelayedTyposInExpr(LHS);
15574 RHS = S.CorrectDelayedTyposInExpr(
15575 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
15576 [Opc, LHS](Expr *E) {
15577 if (Opc != BO_Assign)
15578 return ExprResult(E);
15579 // Avoid correcting the RHS to the same Expr as the LHS.
15580 Decl *D = getDeclFromExpr(E);
15581 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
15584 return std::make_pair(LHS, RHS);
15587 /// Returns true if conversion between vectors of halfs and vectors of floats
15588 /// is needed.
15589 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15590 Expr *E0, Expr *E1 = nullptr) {
15591 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
15592 Ctx.getTargetInfo().useFP16ConversionIntrinsics())
15593 return false;
15595 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15596 QualType Ty = E->IgnoreImplicit()->getType();
15598 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15599 // to vectors of floats. Although the element type of the vectors is __fp16,
15600 // the vectors shouldn't be treated as storage-only types. See the
15601 // discussion here: https://reviews.llvm.org/rG825235c140e7
15602 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15603 if (VT->getVectorKind() == VectorKind::Neon)
15604 return false;
15605 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15607 return false;
15610 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15613 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
15614 /// operator @p Opc at location @c TokLoc. This routine only supports
15615 /// built-in operations; ActOnBinOp handles overloaded operators.
15616 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
15617 BinaryOperatorKind Opc,
15618 Expr *LHSExpr, Expr *RHSExpr) {
15619 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
15620 // The syntax only allows initializer lists on the RHS of assignment,
15621 // so we don't need to worry about accepting invalid code for
15622 // non-assignment operators.
15623 // C++11 5.17p9:
15624 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15625 // of x = {} is x = T().
15626 InitializationKind Kind = InitializationKind::CreateDirectList(
15627 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15628 InitializedEntity Entity =
15629 InitializedEntity::InitializeTemporary(LHSExpr->getType());
15630 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15631 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
15632 if (Init.isInvalid())
15633 return Init;
15634 RHSExpr = Init.get();
15637 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15638 QualType ResultTy; // Result type of the binary operator.
15639 // The following two variables are used for compound assignment operators
15640 QualType CompLHSTy; // Type of LHS after promotions for computation
15641 QualType CompResultTy; // Type of computation result
15642 ExprValueKind VK = VK_PRValue;
15643 ExprObjectKind OK = OK_Ordinary;
15644 bool ConvertHalfVec = false;
15646 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15647 if (!LHS.isUsable() || !RHS.isUsable())
15648 return ExprError();
15650 if (getLangOpts().OpenCL) {
15651 QualType LHSTy = LHSExpr->getType();
15652 QualType RHSTy = RHSExpr->getType();
15653 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15654 // the ATOMIC_VAR_INIT macro.
15655 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15656 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15657 if (BO_Assign == Opc)
15658 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15659 else
15660 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15661 return ExprError();
15664 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15665 // only with a builtin functions and therefore should be disallowed here.
15666 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15667 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15668 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15669 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15670 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15671 return ExprError();
15675 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15676 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15678 switch (Opc) {
15679 case BO_Assign:
15680 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
15681 if (getLangOpts().CPlusPlus &&
15682 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15683 VK = LHS.get()->getValueKind();
15684 OK = LHS.get()->getObjectKind();
15686 if (!ResultTy.isNull()) {
15687 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15688 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
15690 // Avoid copying a block to the heap if the block is assigned to a local
15691 // auto variable that is declared in the same scope as the block. This
15692 // optimization is unsafe if the local variable is declared in an outer
15693 // scope. For example:
15695 // BlockTy b;
15696 // {
15697 // b = ^{...};
15698 // }
15699 // // It is unsafe to invoke the block here if it wasn't copied to the
15700 // // heap.
15701 // b();
15703 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
15704 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
15705 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
15706 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15707 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15709 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
15710 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
15711 NTCUC_Assignment, NTCUK_Copy);
15713 RecordModifiableNonNullParam(*this, LHS.get());
15714 break;
15715 case BO_PtrMemD:
15716 case BO_PtrMemI:
15717 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15718 Opc == BO_PtrMemI);
15719 break;
15720 case BO_Mul:
15721 case BO_Div:
15722 ConvertHalfVec = true;
15723 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
15724 Opc == BO_Div);
15725 break;
15726 case BO_Rem:
15727 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
15728 break;
15729 case BO_Add:
15730 ConvertHalfVec = true;
15731 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
15732 break;
15733 case BO_Sub:
15734 ConvertHalfVec = true;
15735 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
15736 break;
15737 case BO_Shl:
15738 case BO_Shr:
15739 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
15740 break;
15741 case BO_LE:
15742 case BO_LT:
15743 case BO_GE:
15744 case BO_GT:
15745 ConvertHalfVec = true;
15746 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15747 break;
15748 case BO_EQ:
15749 case BO_NE:
15750 ConvertHalfVec = true;
15751 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15752 break;
15753 case BO_Cmp:
15754 ConvertHalfVec = true;
15755 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15756 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15757 break;
15758 case BO_And:
15759 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
15760 [[fallthrough]];
15761 case BO_Xor:
15762 case BO_Or:
15763 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15764 break;
15765 case BO_LAnd:
15766 case BO_LOr:
15767 ConvertHalfVec = true;
15768 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
15769 break;
15770 case BO_MulAssign:
15771 case BO_DivAssign:
15772 ConvertHalfVec = true;
15773 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
15774 Opc == BO_DivAssign);
15775 CompLHSTy = CompResultTy;
15776 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15777 ResultTy =
15778 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15779 break;
15780 case BO_RemAssign:
15781 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
15782 CompLHSTy = CompResultTy;
15783 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15784 ResultTy =
15785 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15786 break;
15787 case BO_AddAssign:
15788 ConvertHalfVec = true;
15789 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15790 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15791 ResultTy =
15792 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15793 break;
15794 case BO_SubAssign:
15795 ConvertHalfVec = true;
15796 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
15797 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15798 ResultTy =
15799 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15800 break;
15801 case BO_ShlAssign:
15802 case BO_ShrAssign:
15803 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15804 CompLHSTy = CompResultTy;
15805 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15806 ResultTy =
15807 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15808 break;
15809 case BO_AndAssign:
15810 case BO_OrAssign: // fallthrough
15811 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15812 [[fallthrough]];
15813 case BO_XorAssign:
15814 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15815 CompLHSTy = CompResultTy;
15816 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15817 ResultTy =
15818 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15819 break;
15820 case BO_Comma:
15821 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15822 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15823 VK = RHS.get()->getValueKind();
15824 OK = RHS.get()->getObjectKind();
15826 break;
15828 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15829 return ExprError();
15831 // Some of the binary operations require promoting operands of half vector to
15832 // float vectors and truncating the result back to half vector. For now, we do
15833 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15834 // arm64).
15835 assert(
15836 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15837 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15838 "both sides are half vectors or neither sides are");
15839 ConvertHalfVec =
15840 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15842 // Check for array bounds violations for both sides of the BinaryOperator
15843 CheckArrayAccess(LHS.get());
15844 CheckArrayAccess(RHS.get());
15846 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15847 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15848 &Context.Idents.get("object_setClass"),
15849 SourceLocation(), LookupOrdinaryName);
15850 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15851 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15852 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15853 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
15854 "object_setClass(")
15855 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15856 ",")
15857 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15859 else
15860 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15862 else if (const ObjCIvarRefExpr *OIRE =
15863 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15864 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15866 // Opc is not a compound assignment if CompResultTy is null.
15867 if (CompResultTy.isNull()) {
15868 if (ConvertHalfVec)
15869 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15870 OpLoc, CurFPFeatureOverrides());
15871 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15872 VK, OK, OpLoc, CurFPFeatureOverrides());
15875 // Handle compound assignments.
15876 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15877 OK_ObjCProperty) {
15878 VK = VK_LValue;
15879 OK = LHS.get()->getObjectKind();
15882 // The LHS is not converted to the result type for fixed-point compound
15883 // assignment as the common type is computed on demand. Reset the CompLHSTy
15884 // to the LHS type we would have gotten after unary conversions.
15885 if (CompResultTy->isFixedPointType())
15886 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15888 if (ConvertHalfVec)
15889 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15890 OpLoc, CurFPFeatureOverrides());
15892 return CompoundAssignOperator::Create(
15893 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15894 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15897 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15898 /// operators are mixed in a way that suggests that the programmer forgot that
15899 /// comparison operators have higher precedence. The most typical example of
15900 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15901 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
15902 SourceLocation OpLoc, Expr *LHSExpr,
15903 Expr *RHSExpr) {
15904 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15905 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15907 // Check that one of the sides is a comparison operator and the other isn't.
15908 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15909 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15910 if (isLeftComp == isRightComp)
15911 return;
15913 // Bitwise operations are sometimes used as eager logical ops.
15914 // Don't diagnose this.
15915 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15916 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15917 if (isLeftBitwise || isRightBitwise)
15918 return;
15920 SourceRange DiagRange = isLeftComp
15921 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15922 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15923 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15924 SourceRange ParensRange =
15925 isLeftComp
15926 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15927 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15929 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15930 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15931 SuggestParentheses(Self, OpLoc,
15932 Self.PDiag(diag::note_precedence_silence) << OpStr,
15933 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15934 SuggestParentheses(Self, OpLoc,
15935 Self.PDiag(diag::note_precedence_bitwise_first)
15936 << BinaryOperator::getOpcodeStr(Opc),
15937 ParensRange);
15940 /// It accepts a '&&' expr that is inside a '||' one.
15941 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15942 /// in parentheses.
15943 static void
15944 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
15945 BinaryOperator *Bop) {
15946 assert(Bop->getOpcode() == BO_LAnd);
15947 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15948 << Bop->getSourceRange() << OpLoc;
15949 SuggestParentheses(Self, Bop->getOperatorLoc(),
15950 Self.PDiag(diag::note_precedence_silence)
15951 << Bop->getOpcodeStr(),
15952 Bop->getSourceRange());
15955 /// Look for '&&' in the left hand of a '||' expr.
15956 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
15957 Expr *LHSExpr, Expr *RHSExpr) {
15958 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15959 if (Bop->getOpcode() == BO_LAnd) {
15960 // If it's "string_literal && a || b" don't warn since the precedence
15961 // doesn't matter.
15962 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15963 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15964 } else if (Bop->getOpcode() == BO_LOr) {
15965 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15966 // If it's "a || b && string_literal || c" we didn't warn earlier for
15967 // "a || b && string_literal", but warn now.
15968 if (RBop->getOpcode() == BO_LAnd &&
15969 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15970 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15976 /// Look for '&&' in the right hand of a '||' expr.
15977 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
15978 Expr *LHSExpr, Expr *RHSExpr) {
15979 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15980 if (Bop->getOpcode() == BO_LAnd) {
15981 // If it's "a || b && string_literal" don't warn since the precedence
15982 // doesn't matter.
15983 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15984 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15989 /// Look for bitwise op in the left or right hand of a bitwise op with
15990 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
15991 /// the '&' expression in parentheses.
15992 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
15993 SourceLocation OpLoc, Expr *SubExpr) {
15994 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15995 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15996 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15997 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15998 << Bop->getSourceRange() << OpLoc;
15999 SuggestParentheses(S, Bop->getOperatorLoc(),
16000 S.PDiag(diag::note_precedence_silence)
16001 << Bop->getOpcodeStr(),
16002 Bop->getSourceRange());
16007 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
16008 Expr *SubExpr, StringRef Shift) {
16009 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
16010 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
16011 StringRef Op = Bop->getOpcodeStr();
16012 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
16013 << Bop->getSourceRange() << OpLoc << Shift << Op;
16014 SuggestParentheses(S, Bop->getOperatorLoc(),
16015 S.PDiag(diag::note_precedence_silence) << Op,
16016 Bop->getSourceRange());
16021 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
16022 Expr *LHSExpr, Expr *RHSExpr) {
16023 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
16024 if (!OCE)
16025 return;
16027 FunctionDecl *FD = OCE->getDirectCallee();
16028 if (!FD || !FD->isOverloadedOperator())
16029 return;
16031 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
16032 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
16033 return;
16035 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
16036 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
16037 << (Kind == OO_LessLess);
16038 SuggestParentheses(S, OCE->getOperatorLoc(),
16039 S.PDiag(diag::note_precedence_silence)
16040 << (Kind == OO_LessLess ? "<<" : ">>"),
16041 OCE->getSourceRange());
16042 SuggestParentheses(
16043 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
16044 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
16047 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
16048 /// precedence.
16049 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
16050 SourceLocation OpLoc, Expr *LHSExpr,
16051 Expr *RHSExpr){
16052 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
16053 if (BinaryOperator::isBitwiseOp(Opc))
16054 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
16056 // Diagnose "arg1 & arg2 | arg3"
16057 if ((Opc == BO_Or || Opc == BO_Xor) &&
16058 !OpLoc.isMacroID()/* Don't warn in macros. */) {
16059 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
16060 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
16063 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
16064 // We don't warn for 'assert(a || b && "bad")' since this is safe.
16065 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
16066 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
16067 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
16070 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
16071 || Opc == BO_Shr) {
16072 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
16073 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
16074 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
16077 // Warn on overloaded shift operators and comparisons, such as:
16078 // cout << 5 == 4;
16079 if (BinaryOperator::isComparisonOp(Opc))
16080 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
16083 // Binary Operators. 'Tok' is the token for the operator.
16084 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
16085 tok::TokenKind Kind,
16086 Expr *LHSExpr, Expr *RHSExpr) {
16087 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
16088 assert(LHSExpr && "ActOnBinOp(): missing left expression");
16089 assert(RHSExpr && "ActOnBinOp(): missing right expression");
16091 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
16092 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
16094 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
16097 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
16098 UnresolvedSetImpl &Functions) {
16099 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
16100 if (OverOp != OO_None && OverOp != OO_Equal)
16101 LookupOverloadedOperatorName(OverOp, S, Functions);
16103 // In C++20 onwards, we may have a second operator to look up.
16104 if (getLangOpts().CPlusPlus20) {
16105 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
16106 LookupOverloadedOperatorName(ExtraOp, S, Functions);
16110 /// Build an overloaded binary operator expression in the given scope.
16111 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
16112 BinaryOperatorKind Opc,
16113 Expr *LHS, Expr *RHS) {
16114 switch (Opc) {
16115 case BO_Assign:
16116 // In the non-overloaded case, we warn about self-assignment (x = x) for
16117 // both simple assignment and certain compound assignments where algebra
16118 // tells us the operation yields a constant result. When the operator is
16119 // overloaded, we can't do the latter because we don't want to assume that
16120 // those algebraic identities still apply; for example, a path-building
16121 // library might use operator/= to append paths. But it's still reasonable
16122 // to assume that simple assignment is just moving/copying values around
16123 // and so self-assignment is likely a bug.
16124 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
16125 [[fallthrough]];
16126 case BO_DivAssign:
16127 case BO_RemAssign:
16128 case BO_SubAssign:
16129 case BO_AndAssign:
16130 case BO_OrAssign:
16131 case BO_XorAssign:
16132 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
16133 break;
16134 default:
16135 break;
16138 // Find all of the overloaded operators visible from this point.
16139 UnresolvedSet<16> Functions;
16140 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
16142 // Build the (potentially-overloaded, potentially-dependent)
16143 // binary operation.
16144 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
16147 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
16148 BinaryOperatorKind Opc,
16149 Expr *LHSExpr, Expr *RHSExpr) {
16150 ExprResult LHS, RHS;
16151 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
16152 if (!LHS.isUsable() || !RHS.isUsable())
16153 return ExprError();
16154 LHSExpr = LHS.get();
16155 RHSExpr = RHS.get();
16157 // We want to end up calling one of checkPseudoObjectAssignment
16158 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
16159 // both expressions are overloadable or either is type-dependent),
16160 // or CreateBuiltinBinOp (in any other case). We also want to get
16161 // any placeholder types out of the way.
16163 // Handle pseudo-objects in the LHS.
16164 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
16165 // Assignments with a pseudo-object l-value need special analysis.
16166 if (pty->getKind() == BuiltinType::PseudoObject &&
16167 BinaryOperator::isAssignmentOp(Opc))
16168 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
16170 // Don't resolve overloads if the other type is overloadable.
16171 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
16172 // We can't actually test that if we still have a placeholder,
16173 // though. Fortunately, none of the exceptions we see in that
16174 // code below are valid when the LHS is an overload set. Note
16175 // that an overload set can be dependently-typed, but it never
16176 // instantiates to having an overloadable type.
16177 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16178 if (resolvedRHS.isInvalid()) return ExprError();
16179 RHSExpr = resolvedRHS.get();
16181 if (RHSExpr->isTypeDependent() ||
16182 RHSExpr->getType()->isOverloadableType())
16183 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16186 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
16187 // template, diagnose the missing 'template' keyword instead of diagnosing
16188 // an invalid use of a bound member function.
16190 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
16191 // to C++1z [over.over]/1.4, but we already checked for that case above.
16192 if (Opc == BO_LT && inTemplateInstantiation() &&
16193 (pty->getKind() == BuiltinType::BoundMember ||
16194 pty->getKind() == BuiltinType::Overload)) {
16195 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
16196 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
16197 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
16198 return isa<FunctionTemplateDecl>(ND);
16199 })) {
16200 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
16201 : OE->getNameLoc(),
16202 diag::err_template_kw_missing)
16203 << OE->getName().getAsString() << "";
16204 return ExprError();
16208 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
16209 if (LHS.isInvalid()) return ExprError();
16210 LHSExpr = LHS.get();
16213 // Handle pseudo-objects in the RHS.
16214 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
16215 // An overload in the RHS can potentially be resolved by the type
16216 // being assigned to.
16217 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
16218 if (getLangOpts().CPlusPlus &&
16219 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16220 LHSExpr->getType()->isOverloadableType()))
16221 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16223 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
16226 // Don't resolve overloads if the other type is overloadable.
16227 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
16228 LHSExpr->getType()->isOverloadableType())
16229 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16231 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16232 if (!resolvedRHS.isUsable()) return ExprError();
16233 RHSExpr = resolvedRHS.get();
16236 if (getLangOpts().CPlusPlus) {
16237 // If either expression is type-dependent, always build an
16238 // overloaded op.
16239 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
16240 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16242 // Otherwise, build an overloaded op if either expression has an
16243 // overloadable type.
16244 if (LHSExpr->getType()->isOverloadableType() ||
16245 RHSExpr->getType()->isOverloadableType())
16246 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16249 if (getLangOpts().RecoveryAST &&
16250 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
16251 assert(!getLangOpts().CPlusPlus);
16252 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
16253 "Should only occur in error-recovery path.");
16254 if (BinaryOperator::isCompoundAssignmentOp(Opc))
16255 // C [6.15.16] p3:
16256 // An assignment expression has the value of the left operand after the
16257 // assignment, but is not an lvalue.
16258 return CompoundAssignOperator::Create(
16259 Context, LHSExpr, RHSExpr, Opc,
16260 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
16261 OpLoc, CurFPFeatureOverrides());
16262 QualType ResultType;
16263 switch (Opc) {
16264 case BO_Assign:
16265 ResultType = LHSExpr->getType().getUnqualifiedType();
16266 break;
16267 case BO_LT:
16268 case BO_GT:
16269 case BO_LE:
16270 case BO_GE:
16271 case BO_EQ:
16272 case BO_NE:
16273 case BO_LAnd:
16274 case BO_LOr:
16275 // These operators have a fixed result type regardless of operands.
16276 ResultType = Context.IntTy;
16277 break;
16278 case BO_Comma:
16279 ResultType = RHSExpr->getType();
16280 break;
16281 default:
16282 ResultType = Context.DependentTy;
16283 break;
16285 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
16286 VK_PRValue, OK_Ordinary, OpLoc,
16287 CurFPFeatureOverrides());
16290 // Build a built-in binary operation.
16291 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
16294 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
16295 if (T.isNull() || T->isDependentType())
16296 return false;
16298 if (!Ctx.isPromotableIntegerType(T))
16299 return true;
16301 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
16304 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
16305 UnaryOperatorKind Opc, Expr *InputExpr,
16306 bool IsAfterAmp) {
16307 ExprResult Input = InputExpr;
16308 ExprValueKind VK = VK_PRValue;
16309 ExprObjectKind OK = OK_Ordinary;
16310 QualType resultType;
16311 bool CanOverflow = false;
16313 bool ConvertHalfVec = false;
16314 if (getLangOpts().OpenCL) {
16315 QualType Ty = InputExpr->getType();
16316 // The only legal unary operation for atomics is '&'.
16317 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
16318 // OpenCL special types - image, sampler, pipe, and blocks are to be used
16319 // only with a builtin functions and therefore should be disallowed here.
16320 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
16321 || Ty->isBlockPointerType())) {
16322 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16323 << InputExpr->getType()
16324 << Input.get()->getSourceRange());
16328 if (getLangOpts().HLSL && OpLoc.isValid()) {
16329 if (Opc == UO_AddrOf)
16330 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
16331 if (Opc == UO_Deref)
16332 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
16335 switch (Opc) {
16336 case UO_PreInc:
16337 case UO_PreDec:
16338 case UO_PostInc:
16339 case UO_PostDec:
16340 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
16341 OpLoc,
16342 Opc == UO_PreInc ||
16343 Opc == UO_PostInc,
16344 Opc == UO_PreInc ||
16345 Opc == UO_PreDec);
16346 CanOverflow = isOverflowingIntegerType(Context, resultType);
16347 break;
16348 case UO_AddrOf:
16349 resultType = CheckAddressOfOperand(Input, OpLoc);
16350 CheckAddressOfNoDeref(InputExpr);
16351 RecordModifiableNonNullParam(*this, InputExpr);
16352 break;
16353 case UO_Deref: {
16354 Input = DefaultFunctionArrayLvalueConversion(Input.get());
16355 if (Input.isInvalid()) return ExprError();
16356 resultType =
16357 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
16358 break;
16360 case UO_Plus:
16361 case UO_Minus:
16362 CanOverflow = Opc == UO_Minus &&
16363 isOverflowingIntegerType(Context, Input.get()->getType());
16364 Input = UsualUnaryConversions(Input.get());
16365 if (Input.isInvalid()) return ExprError();
16366 // Unary plus and minus require promoting an operand of half vector to a
16367 // float vector and truncating the result back to a half vector. For now, we
16368 // do this only when HalfArgsAndReturns is set (that is, when the target is
16369 // arm or arm64).
16370 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
16372 // If the operand is a half vector, promote it to a float vector.
16373 if (ConvertHalfVec)
16374 Input = convertVector(Input.get(), Context.FloatTy, *this);
16375 resultType = Input.get()->getType();
16376 if (resultType->isDependentType())
16377 break;
16378 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16379 break;
16380 else if (resultType->isVectorType() &&
16381 // The z vector extensions don't allow + or - with bool vectors.
16382 (!Context.getLangOpts().ZVector ||
16383 resultType->castAs<VectorType>()->getVectorKind() !=
16384 VectorKind::AltiVecBool))
16385 break;
16386 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16387 break;
16388 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16389 Opc == UO_Plus &&
16390 resultType->isPointerType())
16391 break;
16393 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16394 << resultType << Input.get()->getSourceRange());
16396 case UO_Not: // bitwise complement
16397 Input = UsualUnaryConversions(Input.get());
16398 if (Input.isInvalid())
16399 return ExprError();
16400 resultType = Input.get()->getType();
16401 if (resultType->isDependentType())
16402 break;
16403 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16404 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16405 // C99 does not support '~' for complex conjugation.
16406 Diag(OpLoc, diag::ext_integer_complement_complex)
16407 << resultType << Input.get()->getSourceRange();
16408 else if (resultType->hasIntegerRepresentation())
16409 break;
16410 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16411 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16412 // on vector float types.
16413 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16414 if (!T->isIntegerType())
16415 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16416 << resultType << Input.get()->getSourceRange());
16417 } else {
16418 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16419 << resultType << Input.get()->getSourceRange());
16421 break;
16423 case UO_LNot: // logical negation
16424 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16425 Input = DefaultFunctionArrayLvalueConversion(Input.get());
16426 if (Input.isInvalid()) return ExprError();
16427 resultType = Input.get()->getType();
16429 // Though we still have to promote half FP to float...
16430 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16431 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
16432 resultType = Context.FloatTy;
16435 // WebAsembly tables can't be used in unary expressions.
16436 if (resultType->isPointerType() &&
16437 resultType->getPointeeType().isWebAssemblyReferenceType()) {
16438 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16439 << resultType << Input.get()->getSourceRange());
16442 if (resultType->isDependentType())
16443 break;
16444 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
16445 // C99 6.5.3.3p1: ok, fallthrough;
16446 if (Context.getLangOpts().CPlusPlus) {
16447 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16448 // operand contextually converted to bool.
16449 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
16450 ScalarTypeToBooleanCastKind(resultType));
16451 } else if (Context.getLangOpts().OpenCL &&
16452 Context.getLangOpts().OpenCLVersion < 120) {
16453 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16454 // operate on scalar float types.
16455 if (!resultType->isIntegerType() && !resultType->isPointerType())
16456 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16457 << resultType << Input.get()->getSourceRange());
16459 } else if (resultType->isExtVectorType()) {
16460 if (Context.getLangOpts().OpenCL &&
16461 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16462 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16463 // operate on vector float types.
16464 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16465 if (!T->isIntegerType())
16466 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16467 << resultType << Input.get()->getSourceRange());
16469 // Vector logical not returns the signed variant of the operand type.
16470 resultType = GetSignedVectorType(resultType);
16471 break;
16472 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
16473 const VectorType *VTy = resultType->castAs<VectorType>();
16474 if (VTy->getVectorKind() != VectorKind::Generic)
16475 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16476 << resultType << Input.get()->getSourceRange());
16478 // Vector logical not returns the signed variant of the operand type.
16479 resultType = GetSignedVectorType(resultType);
16480 break;
16481 } else {
16482 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16483 << resultType << Input.get()->getSourceRange());
16486 // LNot always has type int. C99 6.5.3.3p5.
16487 // In C++, it's bool. C++ 5.3.1p8
16488 resultType = Context.getLogicalOperationType();
16489 break;
16490 case UO_Real:
16491 case UO_Imag:
16492 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
16493 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
16494 // complex l-values to ordinary l-values and all other values to r-values.
16495 if (Input.isInvalid()) return ExprError();
16496 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16497 if (Input.get()->isGLValue() &&
16498 Input.get()->getObjectKind() == OK_Ordinary)
16499 VK = Input.get()->getValueKind();
16500 } else if (!getLangOpts().CPlusPlus) {
16501 // In C, a volatile scalar is read by __imag. In C++, it is not.
16502 Input = DefaultLvalueConversion(Input.get());
16504 break;
16505 case UO_Extension:
16506 resultType = Input.get()->getType();
16507 VK = Input.get()->getValueKind();
16508 OK = Input.get()->getObjectKind();
16509 break;
16510 case UO_Coawait:
16511 // It's unnecessary to represent the pass-through operator co_await in the
16512 // AST; just return the input expression instead.
16513 assert(!Input.get()->getType()->isDependentType() &&
16514 "the co_await expression must be non-dependant before "
16515 "building operator co_await");
16516 return Input;
16518 if (resultType.isNull() || Input.isInvalid())
16519 return ExprError();
16521 // Check for array bounds violations in the operand of the UnaryOperator,
16522 // except for the '*' and '&' operators that have to be handled specially
16523 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16524 // that are explicitly defined as valid by the standard).
16525 if (Opc != UO_AddrOf && Opc != UO_Deref)
16526 CheckArrayAccess(Input.get());
16528 auto *UO =
16529 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
16530 OpLoc, CanOverflow, CurFPFeatureOverrides());
16532 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
16533 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
16534 !isUnevaluatedContext())
16535 ExprEvalContexts.back().PossibleDerefs.insert(UO);
16537 // Convert the result back to a half vector.
16538 if (ConvertHalfVec)
16539 return convertVector(UO, Context.HalfTy, *this);
16540 return UO;
16543 /// Determine whether the given expression is a qualified member
16544 /// access expression, of a form that could be turned into a pointer to member
16545 /// with the address-of operator.
16546 bool Sema::isQualifiedMemberAccess(Expr *E) {
16547 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
16548 if (!DRE->getQualifier())
16549 return false;
16551 ValueDecl *VD = DRE->getDecl();
16552 if (!VD->isCXXClassMember())
16553 return false;
16555 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
16556 return true;
16557 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
16558 return Method->isImplicitObjectMemberFunction();
16560 return false;
16563 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16564 if (!ULE->getQualifier())
16565 return false;
16567 for (NamedDecl *D : ULE->decls()) {
16568 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16569 if (Method->isImplicitObjectMemberFunction())
16570 return true;
16571 } else {
16572 // Overload set does not contain methods.
16573 break;
16577 return false;
16580 return false;
16583 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
16584 UnaryOperatorKind Opc, Expr *Input,
16585 bool IsAfterAmp) {
16586 // First things first: handle placeholders so that the
16587 // overloaded-operator check considers the right type.
16588 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16589 // Increment and decrement of pseudo-object references.
16590 if (pty->getKind() == BuiltinType::PseudoObject &&
16591 UnaryOperator::isIncrementDecrementOp(Opc))
16592 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
16594 // extension is always a builtin operator.
16595 if (Opc == UO_Extension)
16596 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16598 // & gets special logic for several kinds of placeholder.
16599 // The builtin code knows what to do.
16600 if (Opc == UO_AddrOf &&
16601 (pty->getKind() == BuiltinType::Overload ||
16602 pty->getKind() == BuiltinType::UnknownAny ||
16603 pty->getKind() == BuiltinType::BoundMember))
16604 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16606 // Anything else needs to be handled now.
16607 ExprResult Result = CheckPlaceholderExpr(Input);
16608 if (Result.isInvalid()) return ExprError();
16609 Input = Result.get();
16612 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16613 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
16614 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
16615 // Find all of the overloaded operators visible from this point.
16616 UnresolvedSet<16> Functions;
16617 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
16618 if (S && OverOp != OO_None)
16619 LookupOverloadedOperatorName(OverOp, S, Functions);
16621 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
16624 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
16627 // Unary Operators. 'Tok' is the token for the operator.
16628 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
16629 Expr *Input, bool IsAfterAmp) {
16630 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
16631 IsAfterAmp);
16634 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
16635 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
16636 LabelDecl *TheDecl) {
16637 TheDecl->markUsed(Context);
16638 // Create the AST node. The address of a label always has type 'void*'.
16639 auto *Res = new (Context) AddrLabelExpr(
16640 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16642 if (getCurFunction())
16643 getCurFunction()->AddrLabels.push_back(Res);
16645 return Res;
16648 void Sema::ActOnStartStmtExpr() {
16649 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
16650 // Make sure we diagnose jumping into a statement expression.
16651 setFunctionHasBranchProtectedScope();
16654 void Sema::ActOnStmtExprError() {
16655 // Note that function is also called by TreeTransform when leaving a
16656 // StmtExpr scope without rebuilding anything.
16658 DiscardCleanupsInEvaluationContext();
16659 PopExpressionEvaluationContext();
16662 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
16663 SourceLocation RPLoc) {
16664 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
16667 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
16668 SourceLocation RPLoc, unsigned TemplateDepth) {
16669 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16670 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
16672 if (hasAnyUnrecoverableErrorsInThisFunction())
16673 DiscardCleanupsInEvaluationContext();
16674 assert(!Cleanup.exprNeedsCleanups() &&
16675 "cleanups within StmtExpr not correctly bound!");
16676 PopExpressionEvaluationContext();
16678 // FIXME: there are a variety of strange constraints to enforce here, for
16679 // example, it is not possible to goto into a stmt expression apparently.
16680 // More semantic analysis is needed.
16682 // If there are sub-stmts in the compound stmt, take the type of the last one
16683 // as the type of the stmtexpr.
16684 QualType Ty = Context.VoidTy;
16685 bool StmtExprMayBindToTemp = false;
16686 if (!Compound->body_empty()) {
16687 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
16688 if (const auto *LastStmt =
16689 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
16690 if (const Expr *Value = LastStmt->getExprStmt()) {
16691 StmtExprMayBindToTemp = true;
16692 Ty = Value->getType();
16697 // FIXME: Check that expression type is complete/non-abstract; statement
16698 // expressions are not lvalues.
16699 Expr *ResStmtExpr =
16700 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16701 if (StmtExprMayBindToTemp)
16702 return MaybeBindToTemporary(ResStmtExpr);
16703 return ResStmtExpr;
16706 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
16707 if (ER.isInvalid())
16708 return ExprError();
16710 // Do function/array conversion on the last expression, but not
16711 // lvalue-to-rvalue. However, initialize an unqualified type.
16712 ER = DefaultFunctionArrayConversion(ER.get());
16713 if (ER.isInvalid())
16714 return ExprError();
16715 Expr *E = ER.get();
16717 if (E->isTypeDependent())
16718 return E;
16720 // In ARC, if the final expression ends in a consume, splice
16721 // the consume out and bind it later. In the alternate case
16722 // (when dealing with a retainable type), the result
16723 // initialization will create a produce. In both cases the
16724 // result will be +1, and we'll need to balance that out with
16725 // a bind.
16726 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
16727 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16728 return Cast->getSubExpr();
16730 // FIXME: Provide a better location for the initialization.
16731 return PerformCopyInitialization(
16732 InitializedEntity::InitializeStmtExprResult(
16733 E->getBeginLoc(), E->getType().getUnqualifiedType()),
16734 SourceLocation(), E);
16737 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
16738 TypeSourceInfo *TInfo,
16739 ArrayRef<OffsetOfComponent> Components,
16740 SourceLocation RParenLoc) {
16741 QualType ArgTy = TInfo->getType();
16742 bool Dependent = ArgTy->isDependentType();
16743 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16745 // We must have at least one component that refers to the type, and the first
16746 // one is known to be a field designator. Verify that the ArgTy represents
16747 // a struct/union/class.
16748 if (!Dependent && !ArgTy->isRecordType())
16749 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
16750 << ArgTy << TypeRange);
16752 // Type must be complete per C99 7.17p3 because a declaring a variable
16753 // with an incomplete type would be ill-formed.
16754 if (!Dependent
16755 && RequireCompleteType(BuiltinLoc, ArgTy,
16756 diag::err_offsetof_incomplete_type, TypeRange))
16757 return ExprError();
16759 bool DidWarnAboutNonPOD = false;
16760 QualType CurrentType = ArgTy;
16761 SmallVector<OffsetOfNode, 4> Comps;
16762 SmallVector<Expr*, 4> Exprs;
16763 for (const OffsetOfComponent &OC : Components) {
16764 if (OC.isBrackets) {
16765 // Offset of an array sub-field. TODO: Should we allow vector elements?
16766 if (!CurrentType->isDependentType()) {
16767 const ArrayType *AT = Context.getAsArrayType(CurrentType);
16768 if(!AT)
16769 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
16770 << CurrentType);
16771 CurrentType = AT->getElementType();
16772 } else
16773 CurrentType = Context.DependentTy;
16775 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
16776 if (IdxRval.isInvalid())
16777 return ExprError();
16778 Expr *Idx = IdxRval.get();
16780 // The expression must be an integral expression.
16781 // FIXME: An integral constant expression?
16782 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16783 !Idx->getType()->isIntegerType())
16784 return ExprError(
16785 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16786 << Idx->getSourceRange());
16788 // Record this array index.
16789 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16790 Exprs.push_back(Idx);
16791 continue;
16794 // Offset of a field.
16795 if (CurrentType->isDependentType()) {
16796 // We have the offset of a field, but we can't look into the dependent
16797 // type. Just record the identifier of the field.
16798 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16799 CurrentType = Context.DependentTy;
16800 continue;
16803 // We need to have a complete type to look into.
16804 if (RequireCompleteType(OC.LocStart, CurrentType,
16805 diag::err_offsetof_incomplete_type))
16806 return ExprError();
16808 // Look for the designated field.
16809 const RecordType *RC = CurrentType->getAs<RecordType>();
16810 if (!RC)
16811 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16812 << CurrentType);
16813 RecordDecl *RD = RC->getDecl();
16815 // C++ [lib.support.types]p5:
16816 // The macro offsetof accepts a restricted set of type arguments in this
16817 // International Standard. type shall be a POD structure or a POD union
16818 // (clause 9).
16819 // C++11 [support.types]p4:
16820 // If type is not a standard-layout class (Clause 9), the results are
16821 // undefined.
16822 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16823 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16824 unsigned DiagID =
16825 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16826 : diag::ext_offsetof_non_pod_type;
16828 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16829 Diag(BuiltinLoc, DiagID)
16830 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
16831 DidWarnAboutNonPOD = true;
16835 // Look for the field.
16836 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16837 LookupQualifiedName(R, RD);
16838 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16839 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16840 if (!MemberDecl) {
16841 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16842 MemberDecl = IndirectMemberDecl->getAnonField();
16845 if (!MemberDecl) {
16846 // Lookup could be ambiguous when looking up a placeholder variable
16847 // __builtin_offsetof(S, _).
16848 // In that case we would already have emitted a diagnostic
16849 if (!R.isAmbiguous())
16850 Diag(BuiltinLoc, diag::err_no_member)
16851 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
16852 return ExprError();
16855 // C99 7.17p3:
16856 // (If the specified member is a bit-field, the behavior is undefined.)
16858 // We diagnose this as an error.
16859 if (MemberDecl->isBitField()) {
16860 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16861 << MemberDecl->getDeclName()
16862 << SourceRange(BuiltinLoc, RParenLoc);
16863 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16864 return ExprError();
16867 RecordDecl *Parent = MemberDecl->getParent();
16868 if (IndirectMemberDecl)
16869 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16871 // If the member was found in a base class, introduce OffsetOfNodes for
16872 // the base class indirections.
16873 CXXBasePaths Paths;
16874 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
16875 Paths)) {
16876 if (Paths.getDetectedVirtual()) {
16877 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16878 << MemberDecl->getDeclName()
16879 << SourceRange(BuiltinLoc, RParenLoc);
16880 return ExprError();
16883 CXXBasePath &Path = Paths.front();
16884 for (const CXXBasePathElement &B : Path)
16885 Comps.push_back(OffsetOfNode(B.Base));
16888 if (IndirectMemberDecl) {
16889 for (auto *FI : IndirectMemberDecl->chain()) {
16890 assert(isa<FieldDecl>(FI));
16891 Comps.push_back(OffsetOfNode(OC.LocStart,
16892 cast<FieldDecl>(FI), OC.LocEnd));
16894 } else
16895 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16897 CurrentType = MemberDecl->getType().getNonReferenceType();
16900 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16901 Comps, Exprs, RParenLoc);
16904 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
16905 SourceLocation BuiltinLoc,
16906 SourceLocation TypeLoc,
16907 ParsedType ParsedArgTy,
16908 ArrayRef<OffsetOfComponent> Components,
16909 SourceLocation RParenLoc) {
16911 TypeSourceInfo *ArgTInfo;
16912 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16913 if (ArgTy.isNull())
16914 return ExprError();
16916 if (!ArgTInfo)
16917 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16919 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16923 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
16924 Expr *CondExpr,
16925 Expr *LHSExpr, Expr *RHSExpr,
16926 SourceLocation RPLoc) {
16927 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16929 ExprValueKind VK = VK_PRValue;
16930 ExprObjectKind OK = OK_Ordinary;
16931 QualType resType;
16932 bool CondIsTrue = false;
16933 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16934 resType = Context.DependentTy;
16935 } else {
16936 // The conditional expression is required to be a constant expression.
16937 llvm::APSInt condEval(32);
16938 ExprResult CondICE = VerifyIntegerConstantExpression(
16939 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16940 if (CondICE.isInvalid())
16941 return ExprError();
16942 CondExpr = CondICE.get();
16943 CondIsTrue = condEval.getZExtValue();
16945 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16946 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16948 resType = ActiveExpr->getType();
16949 VK = ActiveExpr->getValueKind();
16950 OK = ActiveExpr->getObjectKind();
16953 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16954 resType, VK, OK, RPLoc, CondIsTrue);
16957 //===----------------------------------------------------------------------===//
16958 // Clang Extensions.
16959 //===----------------------------------------------------------------------===//
16961 /// ActOnBlockStart - This callback is invoked when a block literal is started.
16962 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16963 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
16965 if (LangOpts.CPlusPlus) {
16966 MangleNumberingContext *MCtx;
16967 Decl *ManglingContextDecl;
16968 std::tie(MCtx, ManglingContextDecl) =
16969 getCurrentMangleNumberContext(Block->getDeclContext());
16970 if (MCtx) {
16971 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16972 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16976 PushBlockScope(CurScope, Block);
16977 CurContext->addDecl(Block);
16978 if (CurScope)
16979 PushDeclContext(CurScope, Block);
16980 else
16981 CurContext = Block;
16983 getCurBlock()->HasImplicitReturnType = true;
16985 // Enter a new evaluation context to insulate the block from any
16986 // cleanups from the enclosing full-expression.
16987 PushExpressionEvaluationContext(
16988 ExpressionEvaluationContext::PotentiallyEvaluated);
16991 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
16992 Scope *CurScope) {
16993 assert(ParamInfo.getIdentifier() == nullptr &&
16994 "block-id should have no identifier!");
16995 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16996 BlockScopeInfo *CurBlock = getCurBlock();
16998 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
16999 QualType T = Sig->getType();
17001 // FIXME: We should allow unexpanded parameter packs here, but that would,
17002 // in turn, make the block expression contain unexpanded parameter packs.
17003 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
17004 // Drop the parameters.
17005 FunctionProtoType::ExtProtoInfo EPI;
17006 EPI.HasTrailingReturn = false;
17007 EPI.TypeQuals.addConst();
17008 T = Context.getFunctionType(Context.DependentTy, std::nullopt, EPI);
17009 Sig = Context.getTrivialTypeSourceInfo(T);
17012 // GetTypeForDeclarator always produces a function type for a block
17013 // literal signature. Furthermore, it is always a FunctionProtoType
17014 // unless the function was written with a typedef.
17015 assert(T->isFunctionType() &&
17016 "GetTypeForDeclarator made a non-function block signature");
17018 // Look for an explicit signature in that function type.
17019 FunctionProtoTypeLoc ExplicitSignature;
17021 if ((ExplicitSignature = Sig->getTypeLoc()
17022 .getAsAdjusted<FunctionProtoTypeLoc>())) {
17024 // Check whether that explicit signature was synthesized by
17025 // GetTypeForDeclarator. If so, don't save that as part of the
17026 // written signature.
17027 if (ExplicitSignature.getLocalRangeBegin() ==
17028 ExplicitSignature.getLocalRangeEnd()) {
17029 // This would be much cheaper if we stored TypeLocs instead of
17030 // TypeSourceInfos.
17031 TypeLoc Result = ExplicitSignature.getReturnLoc();
17032 unsigned Size = Result.getFullDataSize();
17033 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
17034 Sig->getTypeLoc().initializeFullCopy(Result, Size);
17036 ExplicitSignature = FunctionProtoTypeLoc();
17040 CurBlock->TheDecl->setSignatureAsWritten(Sig);
17041 CurBlock->FunctionType = T;
17043 const auto *Fn = T->castAs<FunctionType>();
17044 QualType RetTy = Fn->getReturnType();
17045 bool isVariadic =
17046 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
17048 CurBlock->TheDecl->setIsVariadic(isVariadic);
17050 // Context.DependentTy is used as a placeholder for a missing block
17051 // return type. TODO: what should we do with declarators like:
17052 // ^ * { ... }
17053 // If the answer is "apply template argument deduction"....
17054 if (RetTy != Context.DependentTy) {
17055 CurBlock->ReturnType = RetTy;
17056 CurBlock->TheDecl->setBlockMissingReturnType(false);
17057 CurBlock->HasImplicitReturnType = false;
17060 // Push block parameters from the declarator if we had them.
17061 SmallVector<ParmVarDecl*, 8> Params;
17062 if (ExplicitSignature) {
17063 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
17064 ParmVarDecl *Param = ExplicitSignature.getParam(I);
17065 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
17066 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
17067 // Diagnose this as an extension in C17 and earlier.
17068 if (!getLangOpts().C23)
17069 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
17071 Params.push_back(Param);
17074 // Fake up parameter variables if we have a typedef, like
17075 // ^ fntype { ... }
17076 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
17077 for (const auto &I : Fn->param_types()) {
17078 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
17079 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
17080 Params.push_back(Param);
17084 // Set the parameters on the block decl.
17085 if (!Params.empty()) {
17086 CurBlock->TheDecl->setParams(Params);
17087 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
17088 /*CheckParameterNames=*/false);
17091 // Finally we can process decl attributes.
17092 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
17094 // Put the parameter variables in scope.
17095 for (auto *AI : CurBlock->TheDecl->parameters()) {
17096 AI->setOwningFunction(CurBlock->TheDecl);
17098 // If this has an identifier, add it to the scope stack.
17099 if (AI->getIdentifier()) {
17100 CheckShadow(CurBlock->TheScope, AI);
17102 PushOnScopeChains(AI, CurBlock->TheScope);
17105 if (AI->isInvalidDecl())
17106 CurBlock->TheDecl->setInvalidDecl();
17110 /// ActOnBlockError - If there is an error parsing a block, this callback
17111 /// is invoked to pop the information about the block from the action impl.
17112 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
17113 // Leave the expression-evaluation context.
17114 DiscardCleanupsInEvaluationContext();
17115 PopExpressionEvaluationContext();
17117 // Pop off CurBlock, handle nested blocks.
17118 PopDeclContext();
17119 PopFunctionScopeInfo();
17122 /// ActOnBlockStmtExpr - This is called when the body of a block statement
17123 /// literal was successfully completed. ^(int x){...}
17124 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
17125 Stmt *Body, Scope *CurScope) {
17126 // If blocks are disabled, emit an error.
17127 if (!LangOpts.Blocks)
17128 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
17130 // Leave the expression-evaluation context.
17131 if (hasAnyUnrecoverableErrorsInThisFunction())
17132 DiscardCleanupsInEvaluationContext();
17133 assert(!Cleanup.exprNeedsCleanups() &&
17134 "cleanups within block not correctly bound!");
17135 PopExpressionEvaluationContext();
17137 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
17138 BlockDecl *BD = BSI->TheDecl;
17140 if (BSI->HasImplicitReturnType)
17141 deduceClosureReturnType(*BSI);
17143 QualType RetTy = Context.VoidTy;
17144 if (!BSI->ReturnType.isNull())
17145 RetTy = BSI->ReturnType;
17147 bool NoReturn = BD->hasAttr<NoReturnAttr>();
17148 QualType BlockTy;
17150 // If the user wrote a function type in some form, try to use that.
17151 if (!BSI->FunctionType.isNull()) {
17152 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
17154 FunctionType::ExtInfo Ext = FTy->getExtInfo();
17155 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
17157 // Turn protoless block types into nullary block types.
17158 if (isa<FunctionNoProtoType>(FTy)) {
17159 FunctionProtoType::ExtProtoInfo EPI;
17160 EPI.ExtInfo = Ext;
17161 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
17163 // Otherwise, if we don't need to change anything about the function type,
17164 // preserve its sugar structure.
17165 } else if (FTy->getReturnType() == RetTy &&
17166 (!NoReturn || FTy->getNoReturnAttr())) {
17167 BlockTy = BSI->FunctionType;
17169 // Otherwise, make the minimal modifications to the function type.
17170 } else {
17171 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
17172 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
17173 EPI.TypeQuals = Qualifiers();
17174 EPI.ExtInfo = Ext;
17175 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
17178 // If we don't have a function type, just build one from nothing.
17179 } else {
17180 FunctionProtoType::ExtProtoInfo EPI;
17181 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
17182 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
17185 DiagnoseUnusedParameters(BD->parameters());
17186 BlockTy = Context.getBlockPointerType(BlockTy);
17188 // If needed, diagnose invalid gotos and switches in the block.
17189 if (getCurFunction()->NeedsScopeChecking() &&
17190 !PP.isCodeCompletionEnabled())
17191 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
17193 BD->setBody(cast<CompoundStmt>(Body));
17195 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
17196 DiagnoseUnguardedAvailabilityViolations(BD);
17198 // Try to apply the named return value optimization. We have to check again
17199 // if we can do this, though, because blocks keep return statements around
17200 // to deduce an implicit return type.
17201 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
17202 !BD->isDependentContext())
17203 computeNRVO(Body, BSI);
17205 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
17206 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
17207 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
17208 NTCUK_Destruct|NTCUK_Copy);
17210 PopDeclContext();
17212 // Set the captured variables on the block.
17213 SmallVector<BlockDecl::Capture, 4> Captures;
17214 for (Capture &Cap : BSI->Captures) {
17215 if (Cap.isInvalid() || Cap.isThisCapture())
17216 continue;
17217 // Cap.getVariable() is always a VarDecl because
17218 // blocks cannot capture structured bindings or other ValueDecl kinds.
17219 auto *Var = cast<VarDecl>(Cap.getVariable());
17220 Expr *CopyExpr = nullptr;
17221 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
17222 if (const RecordType *Record =
17223 Cap.getCaptureType()->getAs<RecordType>()) {
17224 // The capture logic needs the destructor, so make sure we mark it.
17225 // Usually this is unnecessary because most local variables have
17226 // their destructors marked at declaration time, but parameters are
17227 // an exception because it's technically only the call site that
17228 // actually requires the destructor.
17229 if (isa<ParmVarDecl>(Var))
17230 FinalizeVarWithDestructor(Var, Record);
17232 // Enter a separate potentially-evaluated context while building block
17233 // initializers to isolate their cleanups from those of the block
17234 // itself.
17235 // FIXME: Is this appropriate even when the block itself occurs in an
17236 // unevaluated operand?
17237 EnterExpressionEvaluationContext EvalContext(
17238 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
17240 SourceLocation Loc = Cap.getLocation();
17242 ExprResult Result = BuildDeclarationNameExpr(
17243 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
17245 // According to the blocks spec, the capture of a variable from
17246 // the stack requires a const copy constructor. This is not true
17247 // of the copy/move done to move a __block variable to the heap.
17248 if (!Result.isInvalid() &&
17249 !Result.get()->getType().isConstQualified()) {
17250 Result = ImpCastExprToType(Result.get(),
17251 Result.get()->getType().withConst(),
17252 CK_NoOp, VK_LValue);
17255 if (!Result.isInvalid()) {
17256 Result = PerformCopyInitialization(
17257 InitializedEntity::InitializeBlock(Var->getLocation(),
17258 Cap.getCaptureType()),
17259 Loc, Result.get());
17262 // Build a full-expression copy expression if initialization
17263 // succeeded and used a non-trivial constructor. Recover from
17264 // errors by pretending that the copy isn't necessary.
17265 if (!Result.isInvalid() &&
17266 !cast<CXXConstructExpr>(Result.get())->getConstructor()
17267 ->isTrivial()) {
17268 Result = MaybeCreateExprWithCleanups(Result);
17269 CopyExpr = Result.get();
17274 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
17275 CopyExpr);
17276 Captures.push_back(NewCap);
17278 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
17280 // Pop the block scope now but keep it alive to the end of this function.
17281 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
17282 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
17284 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
17286 // If the block isn't obviously global, i.e. it captures anything at
17287 // all, then we need to do a few things in the surrounding context:
17288 if (Result->getBlockDecl()->hasCaptures()) {
17289 // First, this expression has a new cleanup object.
17290 ExprCleanupObjects.push_back(Result->getBlockDecl());
17291 Cleanup.setExprNeedsCleanups(true);
17293 // It also gets a branch-protected scope if any of the captured
17294 // variables needs destruction.
17295 for (const auto &CI : Result->getBlockDecl()->captures()) {
17296 const VarDecl *var = CI.getVariable();
17297 if (var->getType().isDestructedType() != QualType::DK_none) {
17298 setFunctionHasBranchProtectedScope();
17299 break;
17304 if (getCurFunction())
17305 getCurFunction()->addBlock(BD);
17307 if (BD->isInvalidDecl())
17308 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
17309 {Result}, Result->getType());
17310 return Result;
17313 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
17314 SourceLocation RPLoc) {
17315 TypeSourceInfo *TInfo;
17316 GetTypeFromParser(Ty, &TInfo);
17317 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
17320 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
17321 Expr *E, TypeSourceInfo *TInfo,
17322 SourceLocation RPLoc) {
17323 Expr *OrigExpr = E;
17324 bool IsMS = false;
17326 // CUDA device code does not support varargs.
17327 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
17328 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
17329 CUDAFunctionTarget T = IdentifyCUDATarget(F);
17330 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
17331 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
17335 // NVPTX does not support va_arg expression.
17336 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
17337 Context.getTargetInfo().getTriple().isNVPTX())
17338 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
17340 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17341 // as Microsoft ABI on an actual Microsoft platform, where
17342 // __builtin_ms_va_list and __builtin_va_list are the same.)
17343 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
17344 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
17345 QualType MSVaListType = Context.getBuiltinMSVaListType();
17346 if (Context.hasSameType(MSVaListType, E->getType())) {
17347 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
17348 return ExprError();
17349 IsMS = true;
17353 // Get the va_list type
17354 QualType VaListType = Context.getBuiltinVaListType();
17355 if (!IsMS) {
17356 if (VaListType->isArrayType()) {
17357 // Deal with implicit array decay; for example, on x86-64,
17358 // va_list is an array, but it's supposed to decay to
17359 // a pointer for va_arg.
17360 VaListType = Context.getArrayDecayedType(VaListType);
17361 // Make sure the input expression also decays appropriately.
17362 ExprResult Result = UsualUnaryConversions(E);
17363 if (Result.isInvalid())
17364 return ExprError();
17365 E = Result.get();
17366 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17367 // If va_list is a record type and we are compiling in C++ mode,
17368 // check the argument using reference binding.
17369 InitializedEntity Entity = InitializedEntity::InitializeParameter(
17370 Context, Context.getLValueReferenceType(VaListType), false);
17371 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
17372 if (Init.isInvalid())
17373 return ExprError();
17374 E = Init.getAs<Expr>();
17375 } else {
17376 // Otherwise, the va_list argument must be an l-value because
17377 // it is modified by va_arg.
17378 if (!E->isTypeDependent() &&
17379 CheckForModifiableLvalue(E, BuiltinLoc, *this))
17380 return ExprError();
17384 if (!IsMS && !E->isTypeDependent() &&
17385 !Context.hasSameType(VaListType, E->getType()))
17386 return ExprError(
17387 Diag(E->getBeginLoc(),
17388 diag::err_first_argument_to_va_arg_not_of_type_va_list)
17389 << OrigExpr->getType() << E->getSourceRange());
17391 if (!TInfo->getType()->isDependentType()) {
17392 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
17393 diag::err_second_parameter_to_va_arg_incomplete,
17394 TInfo->getTypeLoc()))
17395 return ExprError();
17397 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
17398 TInfo->getType(),
17399 diag::err_second_parameter_to_va_arg_abstract,
17400 TInfo->getTypeLoc()))
17401 return ExprError();
17403 if (!TInfo->getType().isPODType(Context)) {
17404 Diag(TInfo->getTypeLoc().getBeginLoc(),
17405 TInfo->getType()->isObjCLifetimeType()
17406 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17407 : diag::warn_second_parameter_to_va_arg_not_pod)
17408 << TInfo->getType()
17409 << TInfo->getTypeLoc().getSourceRange();
17412 // Check for va_arg where arguments of the given type will be promoted
17413 // (i.e. this va_arg is guaranteed to have undefined behavior).
17414 QualType PromoteType;
17415 if (Context.isPromotableIntegerType(TInfo->getType())) {
17416 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
17417 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17418 // and C23 7.16.1.1p2 says, in part:
17419 // If type is not compatible with the type of the actual next argument
17420 // (as promoted according to the default argument promotions), the
17421 // behavior is undefined, except for the following cases:
17422 // - both types are pointers to qualified or unqualified versions of
17423 // compatible types;
17424 // - one type is compatible with a signed integer type, the other
17425 // type is compatible with the corresponding unsigned integer type,
17426 // and the value is representable in both types;
17427 // - one type is pointer to qualified or unqualified void and the
17428 // other is a pointer to a qualified or unqualified character type;
17429 // - or, the type of the next argument is nullptr_t and type is a
17430 // pointer type that has the same representation and alignment
17431 // requirements as a pointer to a character type.
17432 // Given that type compatibility is the primary requirement (ignoring
17433 // qualifications), you would think we could call typesAreCompatible()
17434 // directly to test this. However, in C++, that checks for *same type*,
17435 // which causes false positives when passing an enumeration type to
17436 // va_arg. Instead, get the underlying type of the enumeration and pass
17437 // that.
17438 QualType UnderlyingType = TInfo->getType();
17439 if (const auto *ET = UnderlyingType->getAs<EnumType>())
17440 UnderlyingType = ET->getDecl()->getIntegerType();
17441 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17442 /*CompareUnqualified*/ true))
17443 PromoteType = QualType();
17445 // If the types are still not compatible, we need to test whether the
17446 // promoted type and the underlying type are the same except for
17447 // signedness. Ask the AST for the correctly corresponding type and see
17448 // if that's compatible.
17449 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17450 PromoteType->isUnsignedIntegerType() !=
17451 UnderlyingType->isUnsignedIntegerType()) {
17452 UnderlyingType =
17453 UnderlyingType->isUnsignedIntegerType()
17454 ? Context.getCorrespondingSignedType(UnderlyingType)
17455 : Context.getCorrespondingUnsignedType(UnderlyingType);
17456 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17457 /*CompareUnqualified*/ true))
17458 PromoteType = QualType();
17461 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
17462 PromoteType = Context.DoubleTy;
17463 if (!PromoteType.isNull())
17464 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
17465 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
17466 << TInfo->getType()
17467 << PromoteType
17468 << TInfo->getTypeLoc().getSourceRange());
17471 QualType T = TInfo->getType().getNonLValueExprType(Context);
17472 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
17475 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
17476 // The type of __null will be int or long, depending on the size of
17477 // pointers on the target.
17478 QualType Ty;
17479 unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);
17480 if (pw == Context.getTargetInfo().getIntWidth())
17481 Ty = Context.IntTy;
17482 else if (pw == Context.getTargetInfo().getLongWidth())
17483 Ty = Context.LongTy;
17484 else if (pw == Context.getTargetInfo().getLongLongWidth())
17485 Ty = Context.LongLongTy;
17486 else {
17487 llvm_unreachable("I don't know size of pointer!");
17490 return new (Context) GNUNullExpr(Ty, TokenLoc);
17493 static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
17494 CXXRecordDecl *ImplDecl = nullptr;
17496 // Fetch the std::source_location::__impl decl.
17497 if (NamespaceDecl *Std = S.getStdNamespace()) {
17498 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
17499 Loc, Sema::LookupOrdinaryName);
17500 if (S.LookupQualifiedName(ResultSL, Std)) {
17501 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17502 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
17503 Loc, Sema::LookupOrdinaryName);
17504 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17505 S.LookupQualifiedName(ResultImpl, SLDecl)) {
17506 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17512 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17513 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
17514 return nullptr;
17517 // Verify that __impl is a trivial struct type, with no base classes, and with
17518 // only the four expected fields.
17519 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17520 ImplDecl->getNumBases() != 0) {
17521 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17522 return nullptr;
17525 unsigned Count = 0;
17526 for (FieldDecl *F : ImplDecl->fields()) {
17527 StringRef Name = F->getName();
17529 if (Name == "_M_file_name") {
17530 if (F->getType() !=
17531 S.Context.getPointerType(S.Context.CharTy.withConst()))
17532 break;
17533 Count++;
17534 } else if (Name == "_M_function_name") {
17535 if (F->getType() !=
17536 S.Context.getPointerType(S.Context.CharTy.withConst()))
17537 break;
17538 Count++;
17539 } else if (Name == "_M_line") {
17540 if (!F->getType()->isIntegerType())
17541 break;
17542 Count++;
17543 } else if (Name == "_M_column") {
17544 if (!F->getType()->isIntegerType())
17545 break;
17546 Count++;
17547 } else {
17548 Count = 100; // invalid
17549 break;
17552 if (Count != 4) {
17553 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17554 return nullptr;
17557 return ImplDecl;
17560 ExprResult Sema::ActOnSourceLocExpr(SourceLocIdentKind Kind,
17561 SourceLocation BuiltinLoc,
17562 SourceLocation RPLoc) {
17563 QualType ResultTy;
17564 switch (Kind) {
17565 case SourceLocIdentKind::File:
17566 case SourceLocIdentKind::FileName:
17567 case SourceLocIdentKind::Function:
17568 case SourceLocIdentKind::FuncSig: {
17569 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
17570 ResultTy =
17571 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
17572 break;
17574 case SourceLocIdentKind::Line:
17575 case SourceLocIdentKind::Column:
17576 ResultTy = Context.UnsignedIntTy;
17577 break;
17578 case SourceLocIdentKind::SourceLocStruct:
17579 if (!StdSourceLocationImplDecl) {
17580 StdSourceLocationImplDecl =
17581 LookupStdSourceLocationImpl(*this, BuiltinLoc);
17582 if (!StdSourceLocationImplDecl)
17583 return ExprError();
17585 ResultTy = Context.getPointerType(
17586 Context.getRecordType(StdSourceLocationImplDecl).withConst());
17587 break;
17590 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
17593 ExprResult Sema::BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
17594 SourceLocation BuiltinLoc,
17595 SourceLocation RPLoc,
17596 DeclContext *ParentContext) {
17597 return new (Context)
17598 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17601 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
17602 bool Diagnose) {
17603 if (!getLangOpts().ObjC)
17604 return false;
17606 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
17607 if (!PT)
17608 return false;
17609 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
17611 // Ignore any parens, implicit casts (should only be
17612 // array-to-pointer decays), and not-so-opaque values. The last is
17613 // important for making this trigger for property assignments.
17614 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
17615 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
17616 if (OV->getSourceExpr())
17617 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
17619 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
17620 if (!PT->isObjCIdType() &&
17621 !(ID && ID->getIdentifier()->isStr("NSString")))
17622 return false;
17623 if (!SL->isOrdinary())
17624 return false;
17626 if (Diagnose) {
17627 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
17628 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
17629 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
17631 return true;
17634 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
17635 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
17636 isa<CXXBoolLiteralExpr>(SrcExpr)) &&
17637 !SrcExpr->isNullPointerConstant(
17638 getASTContext(), Expr::NPC_NeverValueDependent)) {
17639 if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
17640 return false;
17641 if (Diagnose) {
17642 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
17643 << /*number*/1
17644 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
17645 Expr *NumLit =
17646 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
17647 if (NumLit)
17648 Exp = NumLit;
17650 return true;
17653 return false;
17656 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
17657 const Expr *SrcExpr) {
17658 if (!DstType->isFunctionPointerType() ||
17659 !SrcExpr->getType()->isFunctionType())
17660 return false;
17662 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
17663 if (!DRE)
17664 return false;
17666 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
17667 if (!FD)
17668 return false;
17670 return !S.checkAddressOfFunctionIsAvailable(FD,
17671 /*Complain=*/true,
17672 SrcExpr->getBeginLoc());
17675 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
17676 SourceLocation Loc,
17677 QualType DstType, QualType SrcType,
17678 Expr *SrcExpr, AssignmentAction Action,
17679 bool *Complained) {
17680 if (Complained)
17681 *Complained = false;
17683 // Decode the result (notice that AST's are still created for extensions).
17684 bool CheckInferredResultType = false;
17685 bool isInvalid = false;
17686 unsigned DiagKind = 0;
17687 ConversionFixItGenerator ConvHints;
17688 bool MayHaveConvFixit = false;
17689 bool MayHaveFunctionDiff = false;
17690 const ObjCInterfaceDecl *IFace = nullptr;
17691 const ObjCProtocolDecl *PDecl = nullptr;
17693 switch (ConvTy) {
17694 case Compatible:
17695 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17696 return false;
17698 case PointerToInt:
17699 if (getLangOpts().CPlusPlus) {
17700 DiagKind = diag::err_typecheck_convert_pointer_int;
17701 isInvalid = true;
17702 } else {
17703 DiagKind = diag::ext_typecheck_convert_pointer_int;
17705 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17706 MayHaveConvFixit = true;
17707 break;
17708 case IntToPointer:
17709 if (getLangOpts().CPlusPlus) {
17710 DiagKind = diag::err_typecheck_convert_int_pointer;
17711 isInvalid = true;
17712 } else {
17713 DiagKind = diag::ext_typecheck_convert_int_pointer;
17715 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17716 MayHaveConvFixit = true;
17717 break;
17718 case IncompatibleFunctionPointerStrict:
17719 DiagKind =
17720 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17721 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17722 MayHaveConvFixit = true;
17723 break;
17724 case IncompatibleFunctionPointer:
17725 if (getLangOpts().CPlusPlus) {
17726 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17727 isInvalid = true;
17728 } else {
17729 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17731 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17732 MayHaveConvFixit = true;
17733 break;
17734 case IncompatiblePointer:
17735 if (Action == AA_Passing_CFAudited) {
17736 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17737 } else if (getLangOpts().CPlusPlus) {
17738 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17739 isInvalid = true;
17740 } else {
17741 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17743 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17744 SrcType->isObjCObjectPointerType();
17745 if (!CheckInferredResultType) {
17746 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17747 } else if (CheckInferredResultType) {
17748 SrcType = SrcType.getUnqualifiedType();
17749 DstType = DstType.getUnqualifiedType();
17751 MayHaveConvFixit = true;
17752 break;
17753 case IncompatiblePointerSign:
17754 if (getLangOpts().CPlusPlus) {
17755 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17756 isInvalid = true;
17757 } else {
17758 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17760 break;
17761 case FunctionVoidPointer:
17762 if (getLangOpts().CPlusPlus) {
17763 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17764 isInvalid = true;
17765 } else {
17766 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17768 break;
17769 case IncompatiblePointerDiscardsQualifiers: {
17770 // Perform array-to-pointer decay if necessary.
17771 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
17773 isInvalid = true;
17775 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17776 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17777 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17778 DiagKind = diag::err_typecheck_incompatible_address_space;
17779 break;
17781 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17782 DiagKind = diag::err_typecheck_incompatible_ownership;
17783 break;
17786 llvm_unreachable("unknown error case for discarding qualifiers!");
17787 // fallthrough
17789 case CompatiblePointerDiscardsQualifiers:
17790 // If the qualifiers lost were because we were applying the
17791 // (deprecated) C++ conversion from a string literal to a char*
17792 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17793 // Ideally, this check would be performed in
17794 // checkPointerTypesForAssignment. However, that would require a
17795 // bit of refactoring (so that the second argument is an
17796 // expression, rather than a type), which should be done as part
17797 // of a larger effort to fix checkPointerTypesForAssignment for
17798 // C++ semantics.
17799 if (getLangOpts().CPlusPlus &&
17800 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
17801 return false;
17802 if (getLangOpts().CPlusPlus) {
17803 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17804 isInvalid = true;
17805 } else {
17806 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17809 break;
17810 case IncompatibleNestedPointerQualifiers:
17811 if (getLangOpts().CPlusPlus) {
17812 isInvalid = true;
17813 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17814 } else {
17815 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17817 break;
17818 case IncompatibleNestedPointerAddressSpaceMismatch:
17819 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17820 isInvalid = true;
17821 break;
17822 case IntToBlockPointer:
17823 DiagKind = diag::err_int_to_block_pointer;
17824 isInvalid = true;
17825 break;
17826 case IncompatibleBlockPointer:
17827 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17828 isInvalid = true;
17829 break;
17830 case IncompatibleObjCQualifiedId: {
17831 if (SrcType->isObjCQualifiedIdType()) {
17832 const ObjCObjectPointerType *srcOPT =
17833 SrcType->castAs<ObjCObjectPointerType>();
17834 for (auto *srcProto : srcOPT->quals()) {
17835 PDecl = srcProto;
17836 break;
17838 if (const ObjCInterfaceType *IFaceT =
17839 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17840 IFace = IFaceT->getDecl();
17842 else if (DstType->isObjCQualifiedIdType()) {
17843 const ObjCObjectPointerType *dstOPT =
17844 DstType->castAs<ObjCObjectPointerType>();
17845 for (auto *dstProto : dstOPT->quals()) {
17846 PDecl = dstProto;
17847 break;
17849 if (const ObjCInterfaceType *IFaceT =
17850 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17851 IFace = IFaceT->getDecl();
17853 if (getLangOpts().CPlusPlus) {
17854 DiagKind = diag::err_incompatible_qualified_id;
17855 isInvalid = true;
17856 } else {
17857 DiagKind = diag::warn_incompatible_qualified_id;
17859 break;
17861 case IncompatibleVectors:
17862 if (getLangOpts().CPlusPlus) {
17863 DiagKind = diag::err_incompatible_vectors;
17864 isInvalid = true;
17865 } else {
17866 DiagKind = diag::warn_incompatible_vectors;
17868 break;
17869 case IncompatibleObjCWeakRef:
17870 DiagKind = diag::err_arc_weak_unavailable_assign;
17871 isInvalid = true;
17872 break;
17873 case Incompatible:
17874 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17875 if (Complained)
17876 *Complained = true;
17877 return true;
17880 DiagKind = diag::err_typecheck_convert_incompatible;
17881 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17882 MayHaveConvFixit = true;
17883 isInvalid = true;
17884 MayHaveFunctionDiff = true;
17885 break;
17888 QualType FirstType, SecondType;
17889 switch (Action) {
17890 case AA_Assigning:
17891 case AA_Initializing:
17892 // The destination type comes first.
17893 FirstType = DstType;
17894 SecondType = SrcType;
17895 break;
17897 case AA_Returning:
17898 case AA_Passing:
17899 case AA_Passing_CFAudited:
17900 case AA_Converting:
17901 case AA_Sending:
17902 case AA_Casting:
17903 // The source type comes first.
17904 FirstType = SrcType;
17905 SecondType = DstType;
17906 break;
17909 PartialDiagnostic FDiag = PDiag(DiagKind);
17910 AssignmentAction ActionForDiag = Action;
17911 if (Action == AA_Passing_CFAudited)
17912 ActionForDiag = AA_Passing;
17914 FDiag << FirstType << SecondType << ActionForDiag
17915 << SrcExpr->getSourceRange();
17917 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17918 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17919 auto isPlainChar = [](const clang::Type *Type) {
17920 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17921 Type->isSpecificBuiltinType(BuiltinType::Char_U);
17923 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17924 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17927 // If we can fix the conversion, suggest the FixIts.
17928 if (!ConvHints.isNull()) {
17929 for (FixItHint &H : ConvHints.Hints)
17930 FDiag << H;
17933 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17935 if (MayHaveFunctionDiff)
17936 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17938 Diag(Loc, FDiag);
17939 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17940 DiagKind == diag::err_incompatible_qualified_id) &&
17941 PDecl && IFace && !IFace->hasDefinition())
17942 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17943 << IFace << PDecl;
17945 if (SecondType == Context.OverloadTy)
17946 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
17947 FirstType, /*TakingAddress=*/true);
17949 if (CheckInferredResultType)
17950 EmitRelatedResultTypeNote(SrcExpr);
17952 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
17953 EmitRelatedResultTypeNoteForReturn(DstType);
17955 if (Complained)
17956 *Complained = true;
17957 return isInvalid;
17960 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17961 llvm::APSInt *Result,
17962 AllowFoldKind CanFold) {
17963 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17964 public:
17965 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17966 QualType T) override {
17967 return S.Diag(Loc, diag::err_ice_not_integral)
17968 << T << S.LangOpts.CPlusPlus;
17970 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17971 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17973 } Diagnoser;
17975 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17978 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17979 llvm::APSInt *Result,
17980 unsigned DiagID,
17981 AllowFoldKind CanFold) {
17982 class IDDiagnoser : public VerifyICEDiagnoser {
17983 unsigned DiagID;
17985 public:
17986 IDDiagnoser(unsigned DiagID)
17987 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17989 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17990 return S.Diag(Loc, DiagID);
17992 } Diagnoser(DiagID);
17994 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17997 Sema::SemaDiagnosticBuilder
17998 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
17999 QualType T) {
18000 return diagnoseNotICE(S, Loc);
18003 Sema::SemaDiagnosticBuilder
18004 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
18005 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
18008 ExprResult
18009 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
18010 VerifyICEDiagnoser &Diagnoser,
18011 AllowFoldKind CanFold) {
18012 SourceLocation DiagLoc = E->getBeginLoc();
18014 if (getLangOpts().CPlusPlus11) {
18015 // C++11 [expr.const]p5:
18016 // If an expression of literal class type is used in a context where an
18017 // integral constant expression is required, then that class type shall
18018 // have a single non-explicit conversion function to an integral or
18019 // unscoped enumeration type
18020 ExprResult Converted;
18021 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
18022 VerifyICEDiagnoser &BaseDiagnoser;
18023 public:
18024 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
18025 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
18026 BaseDiagnoser.Suppress, true),
18027 BaseDiagnoser(BaseDiagnoser) {}
18029 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
18030 QualType T) override {
18031 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
18034 SemaDiagnosticBuilder diagnoseIncomplete(
18035 Sema &S, SourceLocation Loc, QualType T) override {
18036 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
18039 SemaDiagnosticBuilder diagnoseExplicitConv(
18040 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18041 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
18044 SemaDiagnosticBuilder noteExplicitConv(
18045 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18046 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
18047 << ConvTy->isEnumeralType() << ConvTy;
18050 SemaDiagnosticBuilder diagnoseAmbiguous(
18051 Sema &S, SourceLocation Loc, QualType T) override {
18052 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
18055 SemaDiagnosticBuilder noteAmbiguous(
18056 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18057 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
18058 << ConvTy->isEnumeralType() << ConvTy;
18061 SemaDiagnosticBuilder diagnoseConversion(
18062 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18063 llvm_unreachable("conversion functions are permitted");
18065 } ConvertDiagnoser(Diagnoser);
18067 Converted = PerformContextualImplicitConversion(DiagLoc, E,
18068 ConvertDiagnoser);
18069 if (Converted.isInvalid())
18070 return Converted;
18071 E = Converted.get();
18072 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
18073 return ExprError();
18074 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
18075 // An ICE must be of integral or unscoped enumeration type.
18076 if (!Diagnoser.Suppress)
18077 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
18078 << E->getSourceRange();
18079 return ExprError();
18082 ExprResult RValueExpr = DefaultLvalueConversion(E);
18083 if (RValueExpr.isInvalid())
18084 return ExprError();
18086 E = RValueExpr.get();
18088 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
18089 // in the non-ICE case.
18090 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
18091 if (Result)
18092 *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
18093 if (!isa<ConstantExpr>(E))
18094 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
18095 : ConstantExpr::Create(Context, E);
18096 return E;
18099 Expr::EvalResult EvalResult;
18100 SmallVector<PartialDiagnosticAt, 8> Notes;
18101 EvalResult.Diag = &Notes;
18103 // Try to evaluate the expression, and produce diagnostics explaining why it's
18104 // not a constant expression as a side-effect.
18105 bool Folded =
18106 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
18107 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
18109 if (!isa<ConstantExpr>(E))
18110 E = ConstantExpr::Create(Context, E, EvalResult.Val);
18112 // In C++11, we can rely on diagnostics being produced for any expression
18113 // which is not a constant expression. If no diagnostics were produced, then
18114 // this is a constant expression.
18115 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
18116 if (Result)
18117 *Result = EvalResult.Val.getInt();
18118 return E;
18121 // If our only note is the usual "invalid subexpression" note, just point
18122 // the caret at its location rather than producing an essentially
18123 // redundant note.
18124 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18125 diag::note_invalid_subexpr_in_const_expr) {
18126 DiagLoc = Notes[0].first;
18127 Notes.clear();
18130 if (!Folded || !CanFold) {
18131 if (!Diagnoser.Suppress) {
18132 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
18133 for (const PartialDiagnosticAt &Note : Notes)
18134 Diag(Note.first, Note.second);
18137 return ExprError();
18140 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
18141 for (const PartialDiagnosticAt &Note : Notes)
18142 Diag(Note.first, Note.second);
18144 if (Result)
18145 *Result = EvalResult.Val.getInt();
18146 return E;
18149 namespace {
18150 // Handle the case where we conclude a expression which we speculatively
18151 // considered to be unevaluated is actually evaluated.
18152 class TransformToPE : public TreeTransform<TransformToPE> {
18153 typedef TreeTransform<TransformToPE> BaseTransform;
18155 public:
18156 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
18158 // Make sure we redo semantic analysis
18159 bool AlwaysRebuild() { return true; }
18160 bool ReplacingOriginal() { return true; }
18162 // We need to special-case DeclRefExprs referring to FieldDecls which
18163 // are not part of a member pointer formation; normal TreeTransforming
18164 // doesn't catch this case because of the way we represent them in the AST.
18165 // FIXME: This is a bit ugly; is it really the best way to handle this
18166 // case?
18168 // Error on DeclRefExprs referring to FieldDecls.
18169 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18170 if (isa<FieldDecl>(E->getDecl()) &&
18171 !SemaRef.isUnevaluatedContext())
18172 return SemaRef.Diag(E->getLocation(),
18173 diag::err_invalid_non_static_member_use)
18174 << E->getDecl() << E->getSourceRange();
18176 return BaseTransform::TransformDeclRefExpr(E);
18179 // Exception: filter out member pointer formation
18180 ExprResult TransformUnaryOperator(UnaryOperator *E) {
18181 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
18182 return E;
18184 return BaseTransform::TransformUnaryOperator(E);
18187 // The body of a lambda-expression is in a separate expression evaluation
18188 // context so never needs to be transformed.
18189 // FIXME: Ideally we wouldn't transform the closure type either, and would
18190 // just recreate the capture expressions and lambda expression.
18191 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
18192 return SkipLambdaBody(E, Body);
18197 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
18198 assert(isUnevaluatedContext() &&
18199 "Should only transform unevaluated expressions");
18200 ExprEvalContexts.back().Context =
18201 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
18202 if (isUnevaluatedContext())
18203 return E;
18204 return TransformToPE(*this).TransformExpr(E);
18207 TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
18208 assert(isUnevaluatedContext() &&
18209 "Should only transform unevaluated expressions");
18210 ExprEvalContexts.back().Context =
18211 ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
18212 if (isUnevaluatedContext())
18213 return TInfo;
18214 return TransformToPE(*this).TransformType(TInfo);
18217 void
18218 Sema::PushExpressionEvaluationContext(
18219 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
18220 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18221 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
18222 LambdaContextDecl, ExprContext);
18224 // Discarded statements and immediate contexts nested in other
18225 // discarded statements or immediate context are themselves
18226 // a discarded statement or an immediate context, respectively.
18227 ExprEvalContexts.back().InDiscardedStatement =
18228 ExprEvalContexts[ExprEvalContexts.size() - 2]
18229 .isDiscardedStatementContext();
18231 // C++23 [expr.const]/p15
18232 // An expression or conversion is in an immediate function context if [...]
18233 // it is a subexpression of a manifestly constant-evaluated expression or
18234 // conversion.
18235 const auto &Prev = ExprEvalContexts[ExprEvalContexts.size() - 2];
18236 ExprEvalContexts.back().InImmediateFunctionContext =
18237 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
18239 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
18240 Prev.InImmediateEscalatingFunctionContext;
18242 Cleanup.reset();
18243 if (!MaybeODRUseExprs.empty())
18244 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
18247 void
18248 Sema::PushExpressionEvaluationContext(
18249 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
18250 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
18251 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
18252 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
18255 namespace {
18257 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
18258 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
18259 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
18260 if (E->getOpcode() == UO_Deref)
18261 return CheckPossibleDeref(S, E->getSubExpr());
18262 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
18263 return CheckPossibleDeref(S, E->getBase());
18264 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
18265 return CheckPossibleDeref(S, E->getBase());
18266 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
18267 QualType Inner;
18268 QualType Ty = E->getType();
18269 if (const auto *Ptr = Ty->getAs<PointerType>())
18270 Inner = Ptr->getPointeeType();
18271 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
18272 Inner = Arr->getElementType();
18273 else
18274 return nullptr;
18276 if (Inner->hasAttr(attr::NoDeref))
18277 return E;
18279 return nullptr;
18282 } // namespace
18284 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
18285 for (const Expr *E : Rec.PossibleDerefs) {
18286 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
18287 if (DeclRef) {
18288 const ValueDecl *Decl = DeclRef->getDecl();
18289 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
18290 << Decl->getName() << E->getSourceRange();
18291 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
18292 } else {
18293 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
18294 << E->getSourceRange();
18297 Rec.PossibleDerefs.clear();
18300 /// Check whether E, which is either a discarded-value expression or an
18301 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
18302 /// and if so, remove it from the list of volatile-qualified assignments that
18303 /// we are going to warn are deprecated.
18304 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
18305 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
18306 return;
18308 // Note: ignoring parens here is not justified by the standard rules, but
18309 // ignoring parentheses seems like a more reasonable approach, and this only
18310 // drives a deprecation warning so doesn't affect conformance.
18311 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
18312 if (BO->getOpcode() == BO_Assign) {
18313 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
18314 llvm::erase(LHSs, BO->getLHS());
18319 void Sema::MarkExpressionAsImmediateEscalating(Expr *E) {
18320 assert(!FunctionScopes.empty() && "Expected a function scope");
18321 assert(getLangOpts().CPlusPlus20 &&
18322 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18323 "Cannot mark an immediate escalating expression outside of an "
18324 "immediate escalating context");
18325 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
18326 Call && Call->getCallee()) {
18327 if (auto *DeclRef =
18328 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18329 DeclRef->setIsImmediateEscalating(true);
18330 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
18331 Ctr->setIsImmediateEscalating(true);
18332 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
18333 DeclRef->setIsImmediateEscalating(true);
18334 } else {
18335 assert(false && "expected an immediately escalating expression");
18337 getCurFunction()->FoundImmediateEscalatingExpression = true;
18340 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
18341 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18342 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18343 isCheckingDefaultArgumentOrInitializer() ||
18344 RebuildingImmediateInvocation || isImmediateFunctionContext())
18345 return E;
18347 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18348 /// It's OK if this fails; we'll also remove this in
18349 /// HandleImmediateInvocations, but catching it here allows us to avoid
18350 /// walking the AST looking for it in simple cases.
18351 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
18352 if (auto *DeclRef =
18353 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18354 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
18356 // C++23 [expr.const]/p16
18357 // An expression or conversion is immediate-escalating if it is not initially
18358 // in an immediate function context and it is [...] an immediate invocation
18359 // that is not a constant expression and is not a subexpression of an
18360 // immediate invocation.
18361 APValue Cached;
18362 auto CheckConstantExpressionAndKeepResult = [&]() {
18363 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18364 Expr::EvalResult Eval;
18365 Eval.Diag = &Notes;
18366 bool Res = E.get()->EvaluateAsConstantExpr(
18367 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
18368 if (Res && Notes.empty()) {
18369 Cached = std::move(Eval.Val);
18370 return true;
18372 return false;
18375 if (!E.get()->isValueDependent() &&
18376 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18377 !CheckConstantExpressionAndKeepResult()) {
18378 MarkExpressionAsImmediateEscalating(E.get());
18379 return E;
18382 if (Cleanup.exprNeedsCleanups()) {
18383 // Since an immediate invocation is a full expression itself - it requires
18384 // an additional ExprWithCleanups node, but it can participate to a bigger
18385 // full expression which actually requires cleanups to be run after so
18386 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18387 // may discard cleanups for outer expression too early.
18389 // Note that ExprWithCleanups created here must always have empty cleanup
18390 // objects:
18391 // - compound literals do not create cleanup objects in C++ and immediate
18392 // invocations are C++-only.
18393 // - blocks are not allowed inside constant expressions and compiler will
18394 // issue an error if they appear there.
18396 // Hence, in correct code any cleanup objects created inside current
18397 // evaluation context must be outside the immediate invocation.
18398 E = ExprWithCleanups::Create(getASTContext(), E.get(),
18399 Cleanup.cleanupsHaveSideEffects(), {});
18402 ConstantExpr *Res = ConstantExpr::Create(
18403 getASTContext(), E.get(),
18404 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
18405 getASTContext()),
18406 /*IsImmediateInvocation*/ true);
18407 if (Cached.hasValue())
18408 Res->MoveIntoResult(Cached, getASTContext());
18409 /// Value-dependent constant expressions should not be immediately
18410 /// evaluated until they are instantiated.
18411 if (!Res->isValueDependent())
18412 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
18413 return Res;
18416 static void EvaluateAndDiagnoseImmediateInvocation(
18417 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
18418 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
18419 Expr::EvalResult Eval;
18420 Eval.Diag = &Notes;
18421 ConstantExpr *CE = Candidate.getPointer();
18422 bool Result = CE->EvaluateAsConstantExpr(
18423 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
18424 if (!Result || !Notes.empty()) {
18425 SemaRef.FailedImmediateInvocations.insert(CE);
18426 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18427 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
18428 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18429 FunctionDecl *FD = nullptr;
18430 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
18431 FD = cast<FunctionDecl>(Call->getCalleeDecl());
18432 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
18433 FD = Call->getConstructor();
18434 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
18435 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
18437 assert(FD && FD->isImmediateFunction() &&
18438 "could not find an immediate function in this expression");
18439 if (FD->isInvalidDecl())
18440 return;
18441 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
18442 << FD << FD->isConsteval();
18443 if (auto Context =
18444 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18445 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18446 << Context->Decl;
18447 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18449 if (!FD->isConsteval())
18450 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18451 for (auto &Note : Notes)
18452 SemaRef.Diag(Note.first, Note.second);
18453 return;
18455 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
18458 static void RemoveNestedImmediateInvocation(
18459 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
18460 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
18461 struct ComplexRemove : TreeTransform<ComplexRemove> {
18462 using Base = TreeTransform<ComplexRemove>;
18463 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18464 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
18465 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
18466 CurrentII;
18467 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18468 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
18469 SmallVector<Sema::ImmediateInvocationCandidate,
18470 4>::reverse_iterator Current)
18471 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18472 void RemoveImmediateInvocation(ConstantExpr* E) {
18473 auto It = std::find_if(CurrentII, IISet.rend(),
18474 [E](Sema::ImmediateInvocationCandidate Elem) {
18475 return Elem.getPointer() == E;
18477 // It is possible that some subexpression of the current immediate
18478 // invocation was handled from another expression evaluation context. Do
18479 // not handle the current immediate invocation if some of its
18480 // subexpressions failed before.
18481 if (It == IISet.rend()) {
18482 if (SemaRef.FailedImmediateInvocations.contains(E))
18483 CurrentII->setInt(1);
18484 } else {
18485 It->setInt(1); // Mark as deleted
18488 ExprResult TransformConstantExpr(ConstantExpr *E) {
18489 if (!E->isImmediateInvocation())
18490 return Base::TransformConstantExpr(E);
18491 RemoveImmediateInvocation(E);
18492 return Base::TransformExpr(E->getSubExpr());
18494 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18495 /// we need to remove its DeclRefExpr from the DRSet.
18496 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18497 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
18498 return Base::TransformCXXOperatorCallExpr(E);
18500 /// Base::TransformUserDefinedLiteral doesn't preserve the
18501 /// UserDefinedLiteral node.
18502 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18503 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18504 /// here.
18505 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18506 if (!Init)
18507 return Init;
18508 /// ConstantExpr are the first layer of implicit node to be removed so if
18509 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18510 if (auto *CE = dyn_cast<ConstantExpr>(Init))
18511 if (CE->isImmediateInvocation())
18512 RemoveImmediateInvocation(CE);
18513 return Base::TransformInitializer(Init, NotCopyInit);
18515 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18516 DRSet.erase(E);
18517 return E;
18519 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18520 // Do not rebuild lambdas to avoid creating a new type.
18521 // Lambdas have already been processed inside their eval context.
18522 return E;
18524 bool AlwaysRebuild() { return false; }
18525 bool ReplacingOriginal() { return true; }
18526 bool AllowSkippingCXXConstructExpr() {
18527 bool Res = AllowSkippingFirstCXXConstructExpr;
18528 AllowSkippingFirstCXXConstructExpr = true;
18529 return Res;
18531 bool AllowSkippingFirstCXXConstructExpr = true;
18532 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18533 Rec.ImmediateInvocationCandidates, It);
18535 /// CXXConstructExpr with a single argument are getting skipped by
18536 /// TreeTransform in some situtation because they could be implicit. This
18537 /// can only occur for the top-level CXXConstructExpr because it is used
18538 /// nowhere in the expression being transformed therefore will not be rebuilt.
18539 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18540 /// skipping the first CXXConstructExpr.
18541 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
18542 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18544 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
18545 // The result may not be usable in case of previous compilation errors.
18546 // In this case evaluation of the expression may result in crash so just
18547 // don't do anything further with the result.
18548 if (Res.isUsable()) {
18549 Res = SemaRef.MaybeCreateExprWithCleanups(Res);
18550 It->getPointer()->setSubExpr(Res.get());
18554 static void
18555 HandleImmediateInvocations(Sema &SemaRef,
18556 Sema::ExpressionEvaluationContextRecord &Rec) {
18557 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18558 Rec.ReferenceToConsteval.size() == 0) ||
18559 SemaRef.RebuildingImmediateInvocation)
18560 return;
18562 /// When we have more than 1 ImmediateInvocationCandidates or previously
18563 /// failed immediate invocations, we need to check for nested
18564 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18565 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18566 /// invocation.
18567 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18568 !SemaRef.FailedImmediateInvocations.empty()) {
18570 /// Prevent sema calls during the tree transform from adding pointers that
18571 /// are already in the sets.
18572 llvm::SaveAndRestore DisableIITracking(
18573 SemaRef.RebuildingImmediateInvocation, true);
18575 /// Prevent diagnostic during tree transfrom as they are duplicates
18576 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
18578 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18579 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18580 if (!It->getInt())
18581 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
18582 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18583 Rec.ReferenceToConsteval.size()) {
18584 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
18585 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18586 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18587 bool VisitDeclRefExpr(DeclRefExpr *E) {
18588 DRSet.erase(E);
18589 return DRSet.size();
18591 } Visitor(Rec.ReferenceToConsteval);
18592 Visitor.TraverseStmt(
18593 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18595 for (auto CE : Rec.ImmediateInvocationCandidates)
18596 if (!CE.getInt())
18597 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
18598 for (auto *DR : Rec.ReferenceToConsteval) {
18599 // If the expression is immediate escalating, it is not an error;
18600 // The outer context itself becomes immediate and further errors,
18601 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18602 if (DR->isImmediateEscalating())
18603 continue;
18604 auto *FD = cast<FunctionDecl>(DR->getDecl());
18605 const NamedDecl *ND = FD;
18606 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
18607 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18608 ND = MD->getParent();
18610 // C++23 [expr.const]/p16
18611 // An expression or conversion is immediate-escalating if it is not
18612 // initially in an immediate function context and it is [...] a
18613 // potentially-evaluated id-expression that denotes an immediate function
18614 // that is not a subexpression of an immediate invocation.
18615 bool ImmediateEscalating = false;
18616 bool IsPotentiallyEvaluated =
18617 Rec.Context ==
18618 Sema::ExpressionEvaluationContext::PotentiallyEvaluated ||
18619 Rec.Context ==
18620 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed;
18621 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18622 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18624 if (!Rec.InImmediateEscalatingFunctionContext ||
18625 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18626 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
18627 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
18628 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
18629 if (auto Context =
18630 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
18631 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18632 << Context->Decl;
18633 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18635 if (FD->isImmediateEscalating() && !FD->isConsteval())
18636 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18638 } else {
18639 SemaRef.MarkExpressionAsImmediateEscalating(DR);
18644 void Sema::PopExpressionEvaluationContext() {
18645 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
18646 unsigned NumTypos = Rec.NumTypos;
18648 if (!Rec.Lambdas.empty()) {
18649 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
18650 if (!getLangOpts().CPlusPlus20 &&
18651 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18652 Rec.isUnevaluated() ||
18653 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
18654 unsigned D;
18655 if (Rec.isUnevaluated()) {
18656 // C++11 [expr.prim.lambda]p2:
18657 // A lambda-expression shall not appear in an unevaluated operand
18658 // (Clause 5).
18659 D = diag::err_lambda_unevaluated_operand;
18660 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18661 // C++1y [expr.const]p2:
18662 // A conditional-expression e is a core constant expression unless the
18663 // evaluation of e, following the rules of the abstract machine, would
18664 // evaluate [...] a lambda-expression.
18665 D = diag::err_lambda_in_constant_expression;
18666 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18667 // C++17 [expr.prim.lamda]p2:
18668 // A lambda-expression shall not appear [...] in a template-argument.
18669 D = diag::err_lambda_in_invalid_context;
18670 } else
18671 llvm_unreachable("Couldn't infer lambda error message.");
18673 for (const auto *L : Rec.Lambdas)
18674 Diag(L->getBeginLoc(), D);
18678 WarnOnPendingNoDerefs(Rec);
18679 HandleImmediateInvocations(*this, Rec);
18681 // Warn on any volatile-qualified simple-assignments that are not discarded-
18682 // value expressions nor unevaluated operands (those cases get removed from
18683 // this list by CheckUnusedVolatileAssignment).
18684 for (auto *BO : Rec.VolatileAssignmentLHSs)
18685 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
18686 << BO->getType();
18688 // When are coming out of an unevaluated context, clear out any
18689 // temporaries that we may have created as part of the evaluation of
18690 // the expression in that context: they aren't relevant because they
18691 // will never be constructed.
18692 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18693 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
18694 ExprCleanupObjects.end());
18695 Cleanup = Rec.ParentCleanup;
18696 CleanupVarDeclMarking();
18697 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
18698 // Otherwise, merge the contexts together.
18699 } else {
18700 Cleanup.mergeFrom(Rec.ParentCleanup);
18701 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
18702 Rec.SavedMaybeODRUseExprs.end());
18705 // Pop the current expression evaluation context off the stack.
18706 ExprEvalContexts.pop_back();
18708 // The global expression evaluation context record is never popped.
18709 ExprEvalContexts.back().NumTypos += NumTypos;
18712 void Sema::DiscardCleanupsInEvaluationContext() {
18713 ExprCleanupObjects.erase(
18714 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18715 ExprCleanupObjects.end());
18716 Cleanup.reset();
18717 MaybeODRUseExprs.clear();
18720 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
18721 ExprResult Result = CheckPlaceholderExpr(E);
18722 if (Result.isInvalid())
18723 return ExprError();
18724 E = Result.get();
18725 if (!E->getType()->isVariablyModifiedType())
18726 return E;
18727 return TransformToPotentiallyEvaluated(E);
18730 /// Are we in a context that is potentially constant evaluated per C++20
18731 /// [expr.const]p12?
18732 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
18733 /// C++2a [expr.const]p12:
18734 // An expression or conversion is potentially constant evaluated if it is
18735 switch (SemaRef.ExprEvalContexts.back().Context) {
18736 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
18737 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
18739 // -- a manifestly constant-evaluated expression,
18740 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
18741 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18742 case Sema::ExpressionEvaluationContext::DiscardedStatement:
18743 // -- a potentially-evaluated expression,
18744 case Sema::ExpressionEvaluationContext::UnevaluatedList:
18745 // -- an immediate subexpression of a braced-init-list,
18747 // -- [FIXME] an expression of the form & cast-expression that occurs
18748 // within a templated entity
18749 // -- a subexpression of one of the above that is not a subexpression of
18750 // a nested unevaluated operand.
18751 return true;
18753 case Sema::ExpressionEvaluationContext::Unevaluated:
18754 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
18755 // Expressions in this context are never evaluated.
18756 return false;
18758 llvm_unreachable("Invalid context");
18761 /// Return true if this function has a calling convention that requires mangling
18762 /// in the size of the parameter pack.
18763 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
18764 // These manglings don't do anything on non-Windows or non-x86 platforms, so
18765 // we don't need parameter type sizes.
18766 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
18767 if (!TT.isOSWindows() || !TT.isX86())
18768 return false;
18770 // If this is C++ and this isn't an extern "C" function, parameters do not
18771 // need to be complete. In this case, C++ mangling will apply, which doesn't
18772 // use the size of the parameters.
18773 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18774 return false;
18776 // Stdcall, fastcall, and vectorcall need this special treatment.
18777 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18778 switch (CC) {
18779 case CC_X86StdCall:
18780 case CC_X86FastCall:
18781 case CC_X86VectorCall:
18782 return true;
18783 default:
18784 break;
18786 return false;
18789 /// Require that all of the parameter types of function be complete. Normally,
18790 /// parameter types are only required to be complete when a function is called
18791 /// or defined, but to mangle functions with certain calling conventions, the
18792 /// mangler needs to know the size of the parameter list. In this situation,
18793 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18794 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18795 /// result in a linker error. Clang doesn't implement this behavior, and instead
18796 /// attempts to error at compile time.
18797 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
18798 SourceLocation Loc) {
18799 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18800 FunctionDecl *FD;
18801 ParmVarDecl *Param;
18803 public:
18804 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18805 : FD(FD), Param(Param) {}
18807 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18808 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18809 StringRef CCName;
18810 switch (CC) {
18811 case CC_X86StdCall:
18812 CCName = "stdcall";
18813 break;
18814 case CC_X86FastCall:
18815 CCName = "fastcall";
18816 break;
18817 case CC_X86VectorCall:
18818 CCName = "vectorcall";
18819 break;
18820 default:
18821 llvm_unreachable("CC does not need mangling");
18824 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18825 << Param->getDeclName() << FD->getDeclName() << CCName;
18829 for (ParmVarDecl *Param : FD->parameters()) {
18830 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18831 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18835 namespace {
18836 enum class OdrUseContext {
18837 /// Declarations in this context are not odr-used.
18838 None,
18839 /// Declarations in this context are formally odr-used, but this is a
18840 /// dependent context.
18841 Dependent,
18842 /// Declarations in this context are odr-used but not actually used (yet).
18843 FormallyOdrUsed,
18844 /// Declarations in this context are used.
18845 Used
18849 /// Are we within a context in which references to resolved functions or to
18850 /// variables result in odr-use?
18851 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18852 OdrUseContext Result;
18854 switch (SemaRef.ExprEvalContexts.back().Context) {
18855 case Sema::ExpressionEvaluationContext::Unevaluated:
18856 case Sema::ExpressionEvaluationContext::UnevaluatedList:
18857 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
18858 return OdrUseContext::None;
18860 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
18861 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
18862 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
18863 Result = OdrUseContext::Used;
18864 break;
18866 case Sema::ExpressionEvaluationContext::DiscardedStatement:
18867 Result = OdrUseContext::FormallyOdrUsed;
18868 break;
18870 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18871 // A default argument formally results in odr-use, but doesn't actually
18872 // result in a use in any real sense until it itself is used.
18873 Result = OdrUseContext::FormallyOdrUsed;
18874 break;
18877 if (SemaRef.CurContext->isDependentContext())
18878 return OdrUseContext::Dependent;
18880 return Result;
18883 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
18884 if (!Func->isConstexpr())
18885 return false;
18887 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18888 return true;
18889 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18890 return CCD && CCD->getInheritedConstructor();
18893 /// Mark a function referenced, and check whether it is odr-used
18894 /// (C++ [basic.def.odr]p2, C99 6.9p3)
18895 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
18896 bool MightBeOdrUse) {
18897 assert(Func && "No function?");
18899 Func->setReferenced();
18901 // Recursive functions aren't really used until they're used from some other
18902 // context.
18903 bool IsRecursiveCall = CurContext == Func;
18905 // C++11 [basic.def.odr]p3:
18906 // A function whose name appears as a potentially-evaluated expression is
18907 // odr-used if it is the unique lookup result or the selected member of a
18908 // set of overloaded functions [...].
18910 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18911 // can just check that here.
18912 OdrUseContext OdrUse =
18913 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18914 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18915 OdrUse = OdrUseContext::FormallyOdrUsed;
18917 // Trivial default constructors and destructors are never actually used.
18918 // FIXME: What about other special members?
18919 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18920 OdrUse == OdrUseContext::Used) {
18921 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18922 if (Constructor->isDefaultConstructor())
18923 OdrUse = OdrUseContext::FormallyOdrUsed;
18924 if (isa<CXXDestructorDecl>(Func))
18925 OdrUse = OdrUseContext::FormallyOdrUsed;
18928 // C++20 [expr.const]p12:
18929 // A function [...] is needed for constant evaluation if it is [...] a
18930 // constexpr function that is named by an expression that is potentially
18931 // constant evaluated
18932 bool NeededForConstantEvaluation =
18933 isPotentiallyConstantEvaluatedContext(*this) &&
18934 isImplicitlyDefinableConstexprFunction(Func);
18936 // Determine whether we require a function definition to exist, per
18937 // C++11 [temp.inst]p3:
18938 // Unless a function template specialization has been explicitly
18939 // instantiated or explicitly specialized, the function template
18940 // specialization is implicitly instantiated when the specialization is
18941 // referenced in a context that requires a function definition to exist.
18942 // C++20 [temp.inst]p7:
18943 // The existence of a definition of a [...] function is considered to
18944 // affect the semantics of the program if the [...] function is needed for
18945 // constant evaluation by an expression
18946 // C++20 [basic.def.odr]p10:
18947 // Every program shall contain exactly one definition of every non-inline
18948 // function or variable that is odr-used in that program outside of a
18949 // discarded statement
18950 // C++20 [special]p1:
18951 // The implementation will implicitly define [defaulted special members]
18952 // if they are odr-used or needed for constant evaluation.
18954 // Note that we skip the implicit instantiation of templates that are only
18955 // used in unused default arguments or by recursive calls to themselves.
18956 // This is formally non-conforming, but seems reasonable in practice.
18957 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
18958 NeededForConstantEvaluation);
18960 // C++14 [temp.expl.spec]p6:
18961 // If a template [...] is explicitly specialized then that specialization
18962 // shall be declared before the first use of that specialization that would
18963 // cause an implicit instantiation to take place, in every translation unit
18964 // in which such a use occurs
18965 if (NeedDefinition &&
18966 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18967 Func->getMemberSpecializationInfo()))
18968 checkSpecializationReachability(Loc, Func);
18970 if (getLangOpts().CUDA)
18971 CheckCUDACall(Loc, Func);
18973 // If we need a definition, try to create one.
18974 if (NeedDefinition && !Func->getBody()) {
18975 runWithSufficientStackSpace(Loc, [&] {
18976 if (CXXConstructorDecl *Constructor =
18977 dyn_cast<CXXConstructorDecl>(Func)) {
18978 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
18979 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18980 if (Constructor->isDefaultConstructor()) {
18981 if (Constructor->isTrivial() &&
18982 !Constructor->hasAttr<DLLExportAttr>())
18983 return;
18984 DefineImplicitDefaultConstructor(Loc, Constructor);
18985 } else if (Constructor->isCopyConstructor()) {
18986 DefineImplicitCopyConstructor(Loc, Constructor);
18987 } else if (Constructor->isMoveConstructor()) {
18988 DefineImplicitMoveConstructor(Loc, Constructor);
18990 } else if (Constructor->getInheritedConstructor()) {
18991 DefineInheritingConstructor(Loc, Constructor);
18993 } else if (CXXDestructorDecl *Destructor =
18994 dyn_cast<CXXDestructorDecl>(Func)) {
18995 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
18996 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18997 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18998 return;
18999 DefineImplicitDestructor(Loc, Destructor);
19001 if (Destructor->isVirtual() && getLangOpts().AppleKext)
19002 MarkVTableUsed(Loc, Destructor->getParent());
19003 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
19004 if (MethodDecl->isOverloadedOperator() &&
19005 MethodDecl->getOverloadedOperator() == OO_Equal) {
19006 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
19007 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
19008 if (MethodDecl->isCopyAssignmentOperator())
19009 DefineImplicitCopyAssignment(Loc, MethodDecl);
19010 else if (MethodDecl->isMoveAssignmentOperator())
19011 DefineImplicitMoveAssignment(Loc, MethodDecl);
19013 } else if (isa<CXXConversionDecl>(MethodDecl) &&
19014 MethodDecl->getParent()->isLambda()) {
19015 CXXConversionDecl *Conversion =
19016 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
19017 if (Conversion->isLambdaToBlockPointerConversion())
19018 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
19019 else
19020 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
19021 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
19022 MarkVTableUsed(Loc, MethodDecl->getParent());
19025 if (Func->isDefaulted() && !Func->isDeleted()) {
19026 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
19027 if (DCK != DefaultedComparisonKind::None)
19028 DefineDefaultedComparison(Loc, Func, DCK);
19031 // Implicit instantiation of function templates and member functions of
19032 // class templates.
19033 if (Func->isImplicitlyInstantiable()) {
19034 TemplateSpecializationKind TSK =
19035 Func->getTemplateSpecializationKindForInstantiation();
19036 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
19037 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19038 if (FirstInstantiation) {
19039 PointOfInstantiation = Loc;
19040 if (auto *MSI = Func->getMemberSpecializationInfo())
19041 MSI->setPointOfInstantiation(Loc);
19042 // FIXME: Notify listener.
19043 else
19044 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19045 } else if (TSK != TSK_ImplicitInstantiation) {
19046 // Use the point of use as the point of instantiation, instead of the
19047 // point of explicit instantiation (which we track as the actual point
19048 // of instantiation). This gives better backtraces in diagnostics.
19049 PointOfInstantiation = Loc;
19052 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
19053 Func->isConstexpr()) {
19054 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
19055 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
19056 CodeSynthesisContexts.size())
19057 PendingLocalImplicitInstantiations.push_back(
19058 std::make_pair(Func, PointOfInstantiation));
19059 else if (Func->isConstexpr())
19060 // Do not defer instantiations of constexpr functions, to avoid the
19061 // expression evaluator needing to call back into Sema if it sees a
19062 // call to such a function.
19063 InstantiateFunctionDefinition(PointOfInstantiation, Func);
19064 else {
19065 Func->setInstantiationIsPending(true);
19066 PendingInstantiations.push_back(
19067 std::make_pair(Func, PointOfInstantiation));
19068 // Notify the consumer that a function was implicitly instantiated.
19069 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
19072 } else {
19073 // Walk redefinitions, as some of them may be instantiable.
19074 for (auto *i : Func->redecls()) {
19075 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
19076 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
19082 // If a constructor was defined in the context of a default parameter
19083 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
19084 // context), its initializers may not be referenced yet.
19085 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
19086 EnterExpressionEvaluationContext EvalContext(
19087 *this,
19088 Constructor->isImmediateFunction()
19089 ? ExpressionEvaluationContext::ImmediateFunctionContext
19090 : ExpressionEvaluationContext::PotentiallyEvaluated,
19091 Constructor);
19092 for (CXXCtorInitializer *Init : Constructor->inits()) {
19093 if (Init->isInClassMemberInitializer())
19094 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
19095 MarkDeclarationsReferencedInExpr(Init->getInit());
19100 // C++14 [except.spec]p17:
19101 // An exception-specification is considered to be needed when:
19102 // - the function is odr-used or, if it appears in an unevaluated operand,
19103 // would be odr-used if the expression were potentially-evaluated;
19105 // Note, we do this even if MightBeOdrUse is false. That indicates that the
19106 // function is a pure virtual function we're calling, and in that case the
19107 // function was selected by overload resolution and we need to resolve its
19108 // exception specification for a different reason.
19109 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
19110 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
19111 ResolveExceptionSpec(Loc, FPT);
19113 // A callee could be called by a host function then by a device function.
19114 // If we only try recording once, we will miss recording the use on device
19115 // side. Therefore keep trying until it is recorded.
19116 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
19117 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(Func))
19118 CUDARecordImplicitHostDeviceFuncUsedByDevice(Func);
19120 // If this is the first "real" use, act on that.
19121 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
19122 // Keep track of used but undefined functions.
19123 if (!Func->isDefined()) {
19124 if (mightHaveNonExternalLinkage(Func))
19125 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19126 else if (Func->getMostRecentDecl()->isInlined() &&
19127 !LangOpts.GNUInline &&
19128 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
19129 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19130 else if (isExternalWithNoLinkageType(Func))
19131 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19134 // Some x86 Windows calling conventions mangle the size of the parameter
19135 // pack into the name. Computing the size of the parameters requires the
19136 // parameter types to be complete. Check that now.
19137 if (funcHasParameterSizeMangling(*this, Func))
19138 CheckCompleteParameterTypesForMangler(*this, Func, Loc);
19140 // In the MS C++ ABI, the compiler emits destructor variants where they are
19141 // used. If the destructor is used here but defined elsewhere, mark the
19142 // virtual base destructors referenced. If those virtual base destructors
19143 // are inline, this will ensure they are defined when emitting the complete
19144 // destructor variant. This checking may be redundant if the destructor is
19145 // provided later in this TU.
19146 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19147 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
19148 CXXRecordDecl *Parent = Dtor->getParent();
19149 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
19150 CheckCompleteDestructorVariant(Loc, Dtor);
19154 Func->markUsed(Context);
19158 /// Directly mark a variable odr-used. Given a choice, prefer to use
19159 /// MarkVariableReferenced since it does additional checks and then
19160 /// calls MarkVarDeclODRUsed.
19161 /// If the variable must be captured:
19162 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
19163 /// - else capture it in the DeclContext that maps to the
19164 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
19165 static void
19166 MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef,
19167 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
19168 // Keep track of used but undefined variables.
19169 // FIXME: We shouldn't suppress this warning for static data members.
19170 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
19171 assert(Var && "expected a capturable variable");
19173 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
19174 (!Var->isExternallyVisible() || Var->isInline() ||
19175 SemaRef.isExternalWithNoLinkageType(Var)) &&
19176 !(Var->isStaticDataMember() && Var->hasInit())) {
19177 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
19178 if (old.isInvalid())
19179 old = Loc;
19181 QualType CaptureType, DeclRefType;
19182 if (SemaRef.LangOpts.OpenMP)
19183 SemaRef.tryCaptureOpenMPLambdas(V);
19184 SemaRef.tryCaptureVariable(V, Loc, Sema::TryCapture_Implicit,
19185 /*EllipsisLoc*/ SourceLocation(),
19186 /*BuildAndDiagnose*/ true, CaptureType,
19187 DeclRefType, FunctionScopeIndexToStopAt);
19189 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
19190 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
19191 auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
19192 auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
19193 if (VarTarget == Sema::CVT_Host &&
19194 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
19195 UserTarget == Sema::CFT_Global)) {
19196 // Diagnose ODR-use of host global variables in device functions.
19197 // Reference of device global variables in host functions is allowed
19198 // through shadow variables therefore it is not diagnosed.
19199 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
19200 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
19201 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
19202 SemaRef.targetDiag(Var->getLocation(),
19203 Var->getType().isConstQualified()
19204 ? diag::note_cuda_const_var_unpromoted
19205 : diag::note_cuda_host_var);
19207 } else if (VarTarget == Sema::CVT_Device &&
19208 !Var->hasAttr<CUDASharedAttr>() &&
19209 (UserTarget == Sema::CFT_Host ||
19210 UserTarget == Sema::CFT_HostDevice)) {
19211 // Record a CUDA/HIP device side variable if it is ODR-used
19212 // by host code. This is done conservatively, when the variable is
19213 // referenced in any of the following contexts:
19214 // - a non-function context
19215 // - a host function
19216 // - a host device function
19217 // This makes the ODR-use of the device side variable by host code to
19218 // be visible in the device compilation for the compiler to be able to
19219 // emit template variables instantiated by host code only and to
19220 // externalize the static device side variable ODR-used by host code.
19221 if (!Var->hasExternalStorage())
19222 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
19223 else if (SemaRef.LangOpts.GPURelocatableDeviceCode)
19224 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var);
19228 V->markUsed(SemaRef.Context);
19231 void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture,
19232 SourceLocation Loc,
19233 unsigned CapturingScopeIndex) {
19234 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
19237 void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc,
19238 ValueDecl *var) {
19239 DeclContext *VarDC = var->getDeclContext();
19241 // If the parameter still belongs to the translation unit, then
19242 // we're actually just using one parameter in the declaration of
19243 // the next.
19244 if (isa<ParmVarDecl>(var) &&
19245 isa<TranslationUnitDecl>(VarDC))
19246 return;
19248 // For C code, don't diagnose about capture if we're not actually in code
19249 // right now; it's impossible to write a non-constant expression outside of
19250 // function context, so we'll get other (more useful) diagnostics later.
19252 // For C++, things get a bit more nasty... it would be nice to suppress this
19253 // diagnostic for certain cases like using a local variable in an array bound
19254 // for a member of a local class, but the correct predicate is not obvious.
19255 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
19256 return;
19258 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
19259 unsigned ContextKind = 3; // unknown
19260 if (isa<CXXMethodDecl>(VarDC) &&
19261 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
19262 ContextKind = 2;
19263 } else if (isa<FunctionDecl>(VarDC)) {
19264 ContextKind = 0;
19265 } else if (isa<BlockDecl>(VarDC)) {
19266 ContextKind = 1;
19269 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
19270 << var << ValueKind << ContextKind << VarDC;
19271 S.Diag(var->getLocation(), diag::note_entity_declared_at)
19272 << var;
19274 // FIXME: Add additional diagnostic info about class etc. which prevents
19275 // capture.
19278 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,
19279 ValueDecl *Var,
19280 bool &SubCapturesAreNested,
19281 QualType &CaptureType,
19282 QualType &DeclRefType) {
19283 // Check whether we've already captured it.
19284 if (CSI->CaptureMap.count(Var)) {
19285 // If we found a capture, any subcaptures are nested.
19286 SubCapturesAreNested = true;
19288 // Retrieve the capture type for this variable.
19289 CaptureType = CSI->getCapture(Var).getCaptureType();
19291 // Compute the type of an expression that refers to this variable.
19292 DeclRefType = CaptureType.getNonReferenceType();
19294 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19295 // are mutable in the sense that user can change their value - they are
19296 // private instances of the captured declarations.
19297 const Capture &Cap = CSI->getCapture(Var);
19298 if (Cap.isCopyCapture() &&
19299 !(isa<LambdaScopeInfo>(CSI) &&
19300 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
19301 !(isa<CapturedRegionScopeInfo>(CSI) &&
19302 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
19303 DeclRefType.addConst();
19304 return true;
19306 return false;
19309 // Only block literals, captured statements, and lambda expressions can
19310 // capture; other scopes don't work.
19311 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC,
19312 ValueDecl *Var,
19313 SourceLocation Loc,
19314 const bool Diagnose,
19315 Sema &S) {
19316 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
19317 return getLambdaAwareParentOfDeclContext(DC);
19319 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19320 if (Underlying) {
19321 if (Underlying->hasLocalStorage() && Diagnose)
19322 diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var);
19324 return nullptr;
19327 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19328 // certain types of variables (unnamed, variably modified types etc.)
19329 // so check for eligibility.
19330 static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var,
19331 SourceLocation Loc, const bool Diagnose,
19332 Sema &S) {
19334 assert((isa<VarDecl, BindingDecl>(Var)) &&
19335 "Only variables and structured bindings can be captured");
19337 bool IsBlock = isa<BlockScopeInfo>(CSI);
19338 bool IsLambda = isa<LambdaScopeInfo>(CSI);
19340 // Lambdas are not allowed to capture unnamed variables
19341 // (e.g. anonymous unions).
19342 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19343 // assuming that's the intent.
19344 if (IsLambda && !Var->getDeclName()) {
19345 if (Diagnose) {
19346 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
19347 S.Diag(Var->getLocation(), diag::note_declared_at);
19349 return false;
19352 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19353 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19354 if (Diagnose) {
19355 S.Diag(Loc, diag::err_ref_vm_type);
19356 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19358 return false;
19360 // Prohibit structs with flexible array members too.
19361 // We cannot capture what is in the tail end of the struct.
19362 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
19363 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
19364 if (Diagnose) {
19365 if (IsBlock)
19366 S.Diag(Loc, diag::err_ref_flexarray_type);
19367 else
19368 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
19369 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19371 return false;
19374 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19375 // Lambdas and captured statements are not allowed to capture __block
19376 // variables; they don't support the expected semantics.
19377 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
19378 if (Diagnose) {
19379 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
19380 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19382 return false;
19384 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19385 if (S.getLangOpts().OpenCL && IsBlock &&
19386 Var->getType()->isBlockPointerType()) {
19387 if (Diagnose)
19388 S.Diag(Loc, diag::err_opencl_block_ref_block);
19389 return false;
19392 if (isa<BindingDecl>(Var)) {
19393 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19394 if (Diagnose)
19395 diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var);
19396 return false;
19397 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19398 S.Diag(Loc, S.LangOpts.CPlusPlus20
19399 ? diag::warn_cxx17_compat_capture_binding
19400 : diag::ext_capture_binding)
19401 << Var;
19402 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19406 return true;
19409 // Returns true if the capture by block was successful.
19410 static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,
19411 SourceLocation Loc, const bool BuildAndDiagnose,
19412 QualType &CaptureType, QualType &DeclRefType,
19413 const bool Nested, Sema &S, bool Invalid) {
19414 bool ByRef = false;
19416 // Blocks are not allowed to capture arrays, excepting OpenCL.
19417 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19418 // (decayed to pointers).
19419 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19420 if (BuildAndDiagnose) {
19421 S.Diag(Loc, diag::err_ref_array_type);
19422 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19423 Invalid = true;
19424 } else {
19425 return false;
19429 // Forbid the block-capture of autoreleasing variables.
19430 if (!Invalid &&
19431 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19432 if (BuildAndDiagnose) {
19433 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
19434 << /*block*/ 0;
19435 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19436 Invalid = true;
19437 } else {
19438 return false;
19442 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19443 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19444 QualType PointeeTy = PT->getPointeeType();
19446 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19447 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
19448 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
19449 if (BuildAndDiagnose) {
19450 SourceLocation VarLoc = Var->getLocation();
19451 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
19452 S.Diag(VarLoc, diag::note_declare_parameter_strong);
19457 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19458 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19459 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
19460 // Block capture by reference does not change the capture or
19461 // declaration reference types.
19462 ByRef = true;
19463 } else {
19464 // Block capture by copy introduces 'const'.
19465 CaptureType = CaptureType.getNonReferenceType().withConst();
19466 DeclRefType = CaptureType;
19469 // Actually capture the variable.
19470 if (BuildAndDiagnose)
19471 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
19472 CaptureType, Invalid);
19474 return !Invalid;
19477 /// Capture the given variable in the captured region.
19478 static bool captureInCapturedRegion(
19479 CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc,
19480 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19481 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
19482 bool IsTopScope, Sema &S, bool Invalid) {
19483 // By default, capture variables by reference.
19484 bool ByRef = true;
19485 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
19486 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
19487 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19488 // Using an LValue reference type is consistent with Lambdas (see below).
19489 if (S.isOpenMPCapturedDecl(Var)) {
19490 bool HasConst = DeclRefType.isConstQualified();
19491 DeclRefType = DeclRefType.getUnqualifiedType();
19492 // Don't lose diagnostics about assignments to const.
19493 if (HasConst)
19494 DeclRefType.addConst();
19496 // Do not capture firstprivates in tasks.
19497 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
19498 OMPC_unknown)
19499 return true;
19500 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
19501 RSI->OpenMPCaptureLevel);
19504 if (ByRef)
19505 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19506 else
19507 CaptureType = DeclRefType;
19509 // Actually capture the variable.
19510 if (BuildAndDiagnose)
19511 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
19512 Loc, SourceLocation(), CaptureType, Invalid);
19514 return !Invalid;
19517 /// Capture the given variable in the lambda.
19518 static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var,
19519 SourceLocation Loc, const bool BuildAndDiagnose,
19520 QualType &CaptureType, QualType &DeclRefType,
19521 const bool RefersToCapturedVariable,
19522 const Sema::TryCaptureKind Kind,
19523 SourceLocation EllipsisLoc, const bool IsTopScope,
19524 Sema &S, bool Invalid) {
19525 // Determine whether we are capturing by reference or by value.
19526 bool ByRef = false;
19527 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
19528 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
19529 } else {
19530 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19533 BindingDecl *BD = dyn_cast<BindingDecl>(Var);
19534 // FIXME: We should support capturing structured bindings in OpenMP.
19535 if (!Invalid && BD && S.LangOpts.OpenMP) {
19536 if (BuildAndDiagnose) {
19537 S.Diag(Loc, diag::err_capture_binding_openmp) << Var;
19538 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19540 Invalid = true;
19543 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19544 CaptureType.getNonReferenceType().isWebAssemblyReferenceType()) {
19545 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
19546 Invalid = true;
19549 // Compute the type of the field that will capture this variable.
19550 if (ByRef) {
19551 // C++11 [expr.prim.lambda]p15:
19552 // An entity is captured by reference if it is implicitly or
19553 // explicitly captured but not captured by copy. It is
19554 // unspecified whether additional unnamed non-static data
19555 // members are declared in the closure type for entities
19556 // captured by reference.
19558 // FIXME: It is not clear whether we want to build an lvalue reference
19559 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19560 // to do the former, while EDG does the latter. Core issue 1249 will
19561 // clarify, but for now we follow GCC because it's a more permissive and
19562 // easily defensible position.
19563 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19564 } else {
19565 // C++11 [expr.prim.lambda]p14:
19566 // For each entity captured by copy, an unnamed non-static
19567 // data member is declared in the closure type. The
19568 // declaration order of these members is unspecified. The type
19569 // of such a data member is the type of the corresponding
19570 // captured entity if the entity is not a reference to an
19571 // object, or the referenced type otherwise. [Note: If the
19572 // captured entity is a reference to a function, the
19573 // corresponding data member is also a reference to a
19574 // function. - end note ]
19575 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19576 if (!RefType->getPointeeType()->isFunctionType())
19577 CaptureType = RefType->getPointeeType();
19580 // Forbid the lambda copy-capture of autoreleasing variables.
19581 if (!Invalid &&
19582 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
19583 if (BuildAndDiagnose) {
19584 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19585 S.Diag(Var->getLocation(), diag::note_previous_decl)
19586 << Var->getDeclName();
19587 Invalid = true;
19588 } else {
19589 return false;
19593 // Make sure that by-copy captures are of a complete and non-abstract type.
19594 if (!Invalid && BuildAndDiagnose) {
19595 if (!CaptureType->isDependentType() &&
19596 S.RequireCompleteSizedType(
19597 Loc, CaptureType,
19598 diag::err_capture_of_incomplete_or_sizeless_type,
19599 Var->getDeclName()))
19600 Invalid = true;
19601 else if (S.RequireNonAbstractType(Loc, CaptureType,
19602 diag::err_capture_of_abstract_type))
19603 Invalid = true;
19607 // Compute the type of a reference to this captured variable.
19608 if (ByRef)
19609 DeclRefType = CaptureType.getNonReferenceType();
19610 else {
19611 // C++ [expr.prim.lambda]p5:
19612 // The closure type for a lambda-expression has a public inline
19613 // function call operator [...]. This function call operator is
19614 // declared const (9.3.1) if and only if the lambda-expression's
19615 // parameter-declaration-clause is not followed by mutable.
19616 DeclRefType = CaptureType.getNonReferenceType();
19617 bool Const = LSI->lambdaCaptureShouldBeConst();
19618 if (Const && !CaptureType->isReferenceType())
19619 DeclRefType.addConst();
19622 // Add the capture.
19623 if (BuildAndDiagnose)
19624 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
19625 Loc, EllipsisLoc, CaptureType, Invalid);
19627 return !Invalid;
19630 static bool canCaptureVariableByCopy(ValueDecl *Var,
19631 const ASTContext &Context) {
19632 // Offer a Copy fix even if the type is dependent.
19633 if (Var->getType()->isDependentType())
19634 return true;
19635 QualType T = Var->getType().getNonReferenceType();
19636 if (T.isTriviallyCopyableType(Context))
19637 return true;
19638 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19640 if (!(RD = RD->getDefinition()))
19641 return false;
19642 if (RD->hasSimpleCopyConstructor())
19643 return true;
19644 if (RD->hasUserDeclaredCopyConstructor())
19645 for (CXXConstructorDecl *Ctor : RD->ctors())
19646 if (Ctor->isCopyConstructor())
19647 return !Ctor->isDeleted();
19649 return false;
19652 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19653 /// default capture. Fixes may be omitted if they aren't allowed by the
19654 /// standard, for example we can't emit a default copy capture fix-it if we
19655 /// already explicitly copy capture capture another variable.
19656 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
19657 ValueDecl *Var) {
19658 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
19659 // Don't offer Capture by copy of default capture by copy fixes if Var is
19660 // known not to be copy constructible.
19661 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
19663 SmallString<32> FixBuffer;
19664 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19665 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19666 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19667 if (ShouldOfferCopyFix) {
19668 // Offer fixes to insert an explicit capture for the variable.
19669 // [] -> [VarName]
19670 // [OtherCapture] -> [OtherCapture, VarName]
19671 FixBuffer.assign({Separator, Var->getName()});
19672 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19673 << Var << /*value*/ 0
19674 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19676 // As above but capture by reference.
19677 FixBuffer.assign({Separator, "&", Var->getName()});
19678 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19679 << Var << /*reference*/ 1
19680 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19683 // Only try to offer default capture if there are no captures excluding this
19684 // and init captures.
19685 // [this]: OK.
19686 // [X = Y]: OK.
19687 // [&A, &B]: Don't offer.
19688 // [A, B]: Don't offer.
19689 if (llvm::any_of(LSI->Captures, [](Capture &C) {
19690 return !C.isThisCapture() && !C.isInitCapture();
19692 return;
19694 // The default capture specifiers, '=' or '&', must appear first in the
19695 // capture body.
19696 SourceLocation DefaultInsertLoc =
19697 LSI->IntroducerRange.getBegin().getLocWithOffset(1);
19699 if (ShouldOfferCopyFix) {
19700 bool CanDefaultCopyCapture = true;
19701 // [=, *this] OK since c++17
19702 // [=, this] OK since c++20
19703 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19704 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19705 ? LSI->getCXXThisCapture().isCopyCapture()
19706 : false;
19707 // We can't use default capture by copy if any captures already specified
19708 // capture by copy.
19709 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
19710 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19711 })) {
19712 FixBuffer.assign({"=", Separator});
19713 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19714 << /*value*/ 0
19715 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19719 // We can't use default capture by reference if any captures already specified
19720 // capture by reference.
19721 if (llvm::none_of(LSI->Captures, [](Capture &C) {
19722 return !C.isInitCapture() && C.isReferenceCapture() &&
19723 !C.isThisCapture();
19724 })) {
19725 FixBuffer.assign({"&", Separator});
19726 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19727 << /*reference*/ 1
19728 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19732 bool Sema::tryCaptureVariable(
19733 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19734 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19735 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19736 // An init-capture is notionally from the context surrounding its
19737 // declaration, but its parent DC is the lambda class.
19738 DeclContext *VarDC = Var->getDeclContext();
19739 DeclContext *DC = CurContext;
19741 // tryCaptureVariable is called every time a DeclRef is formed,
19742 // it can therefore have non-negigible impact on performances.
19743 // For local variables and when there is no capturing scope,
19744 // we can bailout early.
19745 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19746 return true;
19748 const auto *VD = dyn_cast<VarDecl>(Var);
19749 if (VD) {
19750 if (VD->isInitCapture())
19751 VarDC = VarDC->getParent();
19752 } else {
19753 VD = Var->getPotentiallyDecomposedVarDecl();
19755 assert(VD && "Cannot capture a null variable");
19757 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19758 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19759 // We need to sync up the Declaration Context with the
19760 // FunctionScopeIndexToStopAt
19761 if (FunctionScopeIndexToStopAt) {
19762 unsigned FSIndex = FunctionScopes.size() - 1;
19763 while (FSIndex != MaxFunctionScopesIndex) {
19764 DC = getLambdaAwareParentOfDeclContext(DC);
19765 --FSIndex;
19769 // Capture global variables if it is required to use private copy of this
19770 // variable.
19771 bool IsGlobal = !VD->hasLocalStorage();
19772 if (IsGlobal &&
19773 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
19774 MaxFunctionScopesIndex)))
19775 return true;
19777 if (isa<VarDecl>(Var))
19778 Var = cast<VarDecl>(Var->getCanonicalDecl());
19780 // Walk up the stack to determine whether we can capture the variable,
19781 // performing the "simple" checks that don't depend on type. We stop when
19782 // we've either hit the declared scope of the variable or find an existing
19783 // capture of that variable. We start from the innermost capturing-entity
19784 // (the DC) and ensure that all intervening capturing-entities
19785 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19786 // declcontext can either capture the variable or have already captured
19787 // the variable.
19788 CaptureType = Var->getType();
19789 DeclRefType = CaptureType.getNonReferenceType();
19790 bool Nested = false;
19791 bool Explicit = (Kind != TryCapture_Implicit);
19792 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19793 do {
19795 LambdaScopeInfo *LSI = nullptr;
19796 if (!FunctionScopes.empty())
19797 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19798 FunctionScopes[FunctionScopesIndex]);
19800 bool IsInScopeDeclarationContext =
19801 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19803 if (LSI && !LSI->AfterParameterList) {
19804 // This allows capturing parameters from a default value which does not
19805 // seems correct
19806 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
19807 return true;
19809 // If the variable is declared in the current context, there is no need to
19810 // capture it.
19811 if (IsInScopeDeclarationContext &&
19812 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19813 return true;
19815 // Only block literals, captured statements, and lambda expressions can
19816 // capture; other scopes don't work.
19817 DeclContext *ParentDC =
19818 !IsInScopeDeclarationContext
19819 ? DC->getParent()
19820 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
19821 BuildAndDiagnose, *this);
19822 // We need to check for the parent *first* because, if we *have*
19823 // private-captured a global variable, we need to recursively capture it in
19824 // intermediate blocks, lambdas, etc.
19825 if (!ParentDC) {
19826 if (IsGlobal) {
19827 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19828 break;
19830 return true;
19833 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19834 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
19836 // Check whether we've already captured it.
19837 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19838 DeclRefType)) {
19839 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19840 break;
19843 // When evaluating some attributes (like enable_if) we might refer to a
19844 // function parameter appertaining to the same declaration as that
19845 // attribute.
19846 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
19847 Parm && Parm->getDeclContext() == DC)
19848 return true;
19850 // If we are instantiating a generic lambda call operator body,
19851 // we do not want to capture new variables. What was captured
19852 // during either a lambdas transformation or initial parsing
19853 // should be used.
19854 if (isGenericLambdaCallOperatorSpecialization(DC)) {
19855 if (BuildAndDiagnose) {
19856 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19857 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
19858 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19859 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19860 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19861 buildLambdaCaptureFixit(*this, LSI, Var);
19862 } else
19863 diagnoseUncapturableValueReferenceOrBinding(*this, ExprLoc, Var);
19865 return true;
19868 // Try to capture variable-length arrays types.
19869 if (Var->getType()->isVariablyModifiedType()) {
19870 // We're going to walk down into the type and look for VLA
19871 // expressions.
19872 QualType QTy = Var->getType();
19873 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19874 QTy = PVD->getOriginalType();
19875 captureVariablyModifiedType(Context, QTy, CSI);
19878 if (getLangOpts().OpenMP) {
19879 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19880 // OpenMP private variables should not be captured in outer scope, so
19881 // just break here. Similarly, global variables that are captured in a
19882 // target region should not be captured outside the scope of the region.
19883 if (RSI->CapRegionKind == CR_OpenMP) {
19884 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
19885 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19886 // If the variable is private (i.e. not captured) and has variably
19887 // modified type, we still need to capture the type for correct
19888 // codegen in all regions, associated with the construct. Currently,
19889 // it is captured in the innermost captured region only.
19890 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19891 Var->getType()->isVariablyModifiedType()) {
19892 QualType QTy = Var->getType();
19893 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19894 QTy = PVD->getOriginalType();
19895 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
19896 I < E; ++I) {
19897 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19898 FunctionScopes[FunctionScopesIndex - I]);
19899 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19900 "Wrong number of captured regions associated with the "
19901 "OpenMP construct.");
19902 captureVariablyModifiedType(Context, QTy, OuterRSI);
19905 bool IsTargetCap =
19906 IsOpenMPPrivateDecl != OMPC_private &&
19907 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19908 RSI->OpenMPCaptureLevel);
19909 // Do not capture global if it is not privatized in outer regions.
19910 bool IsGlobalCap =
19911 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
19912 RSI->OpenMPCaptureLevel);
19914 // When we detect target captures we are looking from inside the
19915 // target region, therefore we need to propagate the capture from the
19916 // enclosing region. Therefore, the capture is not initially nested.
19917 if (IsTargetCap)
19918 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
19920 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19921 (IsGlobal && !IsGlobalCap)) {
19922 Nested = !IsTargetCap;
19923 bool HasConst = DeclRefType.isConstQualified();
19924 DeclRefType = DeclRefType.getUnqualifiedType();
19925 // Don't lose diagnostics about assignments to const.
19926 if (HasConst)
19927 DeclRefType.addConst();
19928 CaptureType = Context.getLValueReferenceType(DeclRefType);
19929 break;
19934 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
19935 // No capture-default, and this is not an explicit capture
19936 // so cannot capture this variable.
19937 if (BuildAndDiagnose) {
19938 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19939 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19940 auto *LSI = cast<LambdaScopeInfo>(CSI);
19941 if (LSI->Lambda) {
19942 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19943 buildLambdaCaptureFixit(*this, LSI, Var);
19945 // FIXME: If we error out because an outer lambda can not implicitly
19946 // capture a variable that an inner lambda explicitly captures, we
19947 // should have the inner lambda do the explicit capture - because
19948 // it makes for cleaner diagnostics later. This would purely be done
19949 // so that the diagnostic does not misleadingly claim that a variable
19950 // can not be captured by a lambda implicitly even though it is captured
19951 // explicitly. Suggestion:
19952 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19953 // at the function head
19954 // - cache the StartingDeclContext - this must be a lambda
19955 // - captureInLambda in the innermost lambda the variable.
19957 return true;
19959 Explicit = false;
19960 FunctionScopesIndex--;
19961 if (IsInScopeDeclarationContext)
19962 DC = ParentDC;
19963 } while (!VarDC->Equals(DC));
19965 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19966 // computing the type of the capture at each step, checking type-specific
19967 // requirements, and adding captures if requested.
19968 // If the variable had already been captured previously, we start capturing
19969 // at the lambda nested within that one.
19970 bool Invalid = false;
19971 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19972 ++I) {
19973 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
19975 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19976 // certain types of variables (unnamed, variably modified types etc.)
19977 // so check for eligibility.
19978 if (!Invalid)
19979 Invalid =
19980 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
19982 // After encountering an error, if we're actually supposed to capture, keep
19983 // capturing in nested contexts to suppress any follow-on diagnostics.
19984 if (Invalid && !BuildAndDiagnose)
19985 return true;
19987 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
19988 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19989 DeclRefType, Nested, *this, Invalid);
19990 Nested = true;
19991 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19992 Invalid = !captureInCapturedRegion(
19993 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
19994 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
19995 Nested = true;
19996 } else {
19997 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19998 Invalid =
19999 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
20000 DeclRefType, Nested, Kind, EllipsisLoc,
20001 /*IsTopScope*/ I == N - 1, *this, Invalid);
20002 Nested = true;
20005 if (Invalid && !BuildAndDiagnose)
20006 return true;
20008 return Invalid;
20011 bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
20012 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
20013 QualType CaptureType;
20014 QualType DeclRefType;
20015 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
20016 /*BuildAndDiagnose=*/true, CaptureType,
20017 DeclRefType, nullptr);
20020 bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) {
20021 QualType CaptureType;
20022 QualType DeclRefType;
20023 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
20024 /*BuildAndDiagnose=*/false, CaptureType,
20025 DeclRefType, nullptr);
20028 QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) {
20029 QualType CaptureType;
20030 QualType DeclRefType;
20032 // Determine whether we can capture this variable.
20033 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
20034 /*BuildAndDiagnose=*/false, CaptureType,
20035 DeclRefType, nullptr))
20036 return QualType();
20038 return DeclRefType;
20041 namespace {
20042 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
20043 // The produced TemplateArgumentListInfo* points to data stored within this
20044 // object, so should only be used in contexts where the pointer will not be
20045 // used after the CopiedTemplateArgs object is destroyed.
20046 class CopiedTemplateArgs {
20047 bool HasArgs;
20048 TemplateArgumentListInfo TemplateArgStorage;
20049 public:
20050 template<typename RefExpr>
20051 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
20052 if (HasArgs)
20053 E->copyTemplateArgumentsInto(TemplateArgStorage);
20055 operator TemplateArgumentListInfo*()
20056 #ifdef __has_cpp_attribute
20057 #if __has_cpp_attribute(clang::lifetimebound)
20058 [[clang::lifetimebound]]
20059 #endif
20060 #endif
20062 return HasArgs ? &TemplateArgStorage : nullptr;
20067 /// Walk the set of potential results of an expression and mark them all as
20068 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
20070 /// \return A new expression if we found any potential results, ExprEmpty() if
20071 /// not, and ExprError() if we diagnosed an error.
20072 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
20073 NonOdrUseReason NOUR) {
20074 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
20075 // an object that satisfies the requirements for appearing in a
20076 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
20077 // is immediately applied." This function handles the lvalue-to-rvalue
20078 // conversion part.
20080 // If we encounter a node that claims to be an odr-use but shouldn't be, we
20081 // transform it into the relevant kind of non-odr-use node and rebuild the
20082 // tree of nodes leading to it.
20084 // This is a mini-TreeTransform that only transforms a restricted subset of
20085 // nodes (and only certain operands of them).
20087 // Rebuild a subexpression.
20088 auto Rebuild = [&](Expr *Sub) {
20089 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
20092 // Check whether a potential result satisfies the requirements of NOUR.
20093 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
20094 // Any entity other than a VarDecl is always odr-used whenever it's named
20095 // in a potentially-evaluated expression.
20096 auto *VD = dyn_cast<VarDecl>(D);
20097 if (!VD)
20098 return true;
20100 // C++2a [basic.def.odr]p4:
20101 // A variable x whose name appears as a potentially-evalauted expression
20102 // e is odr-used by e unless
20103 // -- x is a reference that is usable in constant expressions, or
20104 // -- x is a variable of non-reference type that is usable in constant
20105 // expressions and has no mutable subobjects, and e is an element of
20106 // the set of potential results of an expression of
20107 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20108 // conversion is applied, or
20109 // -- x is a variable of non-reference type, and e is an element of the
20110 // set of potential results of a discarded-value expression to which
20111 // the lvalue-to-rvalue conversion is not applied
20113 // We check the first bullet and the "potentially-evaluated" condition in
20114 // BuildDeclRefExpr. We check the type requirements in the second bullet
20115 // in CheckLValueToRValueConversionOperand below.
20116 switch (NOUR) {
20117 case NOUR_None:
20118 case NOUR_Unevaluated:
20119 llvm_unreachable("unexpected non-odr-use-reason");
20121 case NOUR_Constant:
20122 // Constant references were handled when they were built.
20123 if (VD->getType()->isReferenceType())
20124 return true;
20125 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
20126 if (RD->hasMutableFields())
20127 return true;
20128 if (!VD->isUsableInConstantExpressions(S.Context))
20129 return true;
20130 break;
20132 case NOUR_Discarded:
20133 if (VD->getType()->isReferenceType())
20134 return true;
20135 break;
20137 return false;
20140 // Mark that this expression does not constitute an odr-use.
20141 auto MarkNotOdrUsed = [&] {
20142 S.MaybeODRUseExprs.remove(E);
20143 if (LambdaScopeInfo *LSI = S.getCurLambda())
20144 LSI->markVariableExprAsNonODRUsed(E);
20147 // C++2a [basic.def.odr]p2:
20148 // The set of potential results of an expression e is defined as follows:
20149 switch (E->getStmtClass()) {
20150 // -- If e is an id-expression, ...
20151 case Expr::DeclRefExprClass: {
20152 auto *DRE = cast<DeclRefExpr>(E);
20153 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
20154 break;
20156 // Rebuild as a non-odr-use DeclRefExpr.
20157 MarkNotOdrUsed();
20158 return DeclRefExpr::Create(
20159 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
20160 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
20161 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
20162 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
20165 case Expr::FunctionParmPackExprClass: {
20166 auto *FPPE = cast<FunctionParmPackExpr>(E);
20167 // If any of the declarations in the pack is odr-used, then the expression
20168 // as a whole constitutes an odr-use.
20169 for (VarDecl *D : *FPPE)
20170 if (IsPotentialResultOdrUsed(D))
20171 return ExprEmpty();
20173 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
20174 // nothing cares about whether we marked this as an odr-use, but it might
20175 // be useful for non-compiler tools.
20176 MarkNotOdrUsed();
20177 break;
20180 // -- If e is a subscripting operation with an array operand...
20181 case Expr::ArraySubscriptExprClass: {
20182 auto *ASE = cast<ArraySubscriptExpr>(E);
20183 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
20184 if (!OldBase->getType()->isArrayType())
20185 break;
20186 ExprResult Base = Rebuild(OldBase);
20187 if (!Base.isUsable())
20188 return Base;
20189 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
20190 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
20191 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
20192 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
20193 ASE->getRBracketLoc());
20196 case Expr::MemberExprClass: {
20197 auto *ME = cast<MemberExpr>(E);
20198 // -- If e is a class member access expression [...] naming a non-static
20199 // data member...
20200 if (isa<FieldDecl>(ME->getMemberDecl())) {
20201 ExprResult Base = Rebuild(ME->getBase());
20202 if (!Base.isUsable())
20203 return Base;
20204 return MemberExpr::Create(
20205 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
20206 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
20207 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
20208 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
20209 ME->getObjectKind(), ME->isNonOdrUse());
20212 if (ME->getMemberDecl()->isCXXInstanceMember())
20213 break;
20215 // -- If e is a class member access expression naming a static data member,
20216 // ...
20217 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
20218 break;
20220 // Rebuild as a non-odr-use MemberExpr.
20221 MarkNotOdrUsed();
20222 return MemberExpr::Create(
20223 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
20224 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
20225 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
20226 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
20229 case Expr::BinaryOperatorClass: {
20230 auto *BO = cast<BinaryOperator>(E);
20231 Expr *LHS = BO->getLHS();
20232 Expr *RHS = BO->getRHS();
20233 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20234 if (BO->getOpcode() == BO_PtrMemD) {
20235 ExprResult Sub = Rebuild(LHS);
20236 if (!Sub.isUsable())
20237 return Sub;
20238 LHS = Sub.get();
20239 // -- If e is a comma expression, ...
20240 } else if (BO->getOpcode() == BO_Comma) {
20241 ExprResult Sub = Rebuild(RHS);
20242 if (!Sub.isUsable())
20243 return Sub;
20244 RHS = Sub.get();
20245 } else {
20246 break;
20248 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
20249 LHS, RHS);
20252 // -- If e has the form (e1)...
20253 case Expr::ParenExprClass: {
20254 auto *PE = cast<ParenExpr>(E);
20255 ExprResult Sub = Rebuild(PE->getSubExpr());
20256 if (!Sub.isUsable())
20257 return Sub;
20258 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
20261 // -- If e is a glvalue conditional expression, ...
20262 // We don't apply this to a binary conditional operator. FIXME: Should we?
20263 case Expr::ConditionalOperatorClass: {
20264 auto *CO = cast<ConditionalOperator>(E);
20265 ExprResult LHS = Rebuild(CO->getLHS());
20266 if (LHS.isInvalid())
20267 return ExprError();
20268 ExprResult RHS = Rebuild(CO->getRHS());
20269 if (RHS.isInvalid())
20270 return ExprError();
20271 if (!LHS.isUsable() && !RHS.isUsable())
20272 return ExprEmpty();
20273 if (!LHS.isUsable())
20274 LHS = CO->getLHS();
20275 if (!RHS.isUsable())
20276 RHS = CO->getRHS();
20277 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
20278 CO->getCond(), LHS.get(), RHS.get());
20281 // [Clang extension]
20282 // -- If e has the form __extension__ e1...
20283 case Expr::UnaryOperatorClass: {
20284 auto *UO = cast<UnaryOperator>(E);
20285 if (UO->getOpcode() != UO_Extension)
20286 break;
20287 ExprResult Sub = Rebuild(UO->getSubExpr());
20288 if (!Sub.isUsable())
20289 return Sub;
20290 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
20291 Sub.get());
20294 // [Clang extension]
20295 // -- If e has the form _Generic(...), the set of potential results is the
20296 // union of the sets of potential results of the associated expressions.
20297 case Expr::GenericSelectionExprClass: {
20298 auto *GSE = cast<GenericSelectionExpr>(E);
20300 SmallVector<Expr *, 4> AssocExprs;
20301 bool AnyChanged = false;
20302 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20303 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20304 if (AssocExpr.isInvalid())
20305 return ExprError();
20306 if (AssocExpr.isUsable()) {
20307 AssocExprs.push_back(AssocExpr.get());
20308 AnyChanged = true;
20309 } else {
20310 AssocExprs.push_back(OrigAssocExpr);
20314 void *ExOrTy = nullptr;
20315 bool IsExpr = GSE->isExprPredicate();
20316 if (IsExpr)
20317 ExOrTy = GSE->getControllingExpr();
20318 else
20319 ExOrTy = GSE->getControllingType();
20320 return AnyChanged ? S.CreateGenericSelectionExpr(
20321 GSE->getGenericLoc(), GSE->getDefaultLoc(),
20322 GSE->getRParenLoc(), IsExpr, ExOrTy,
20323 GSE->getAssocTypeSourceInfos(), AssocExprs)
20324 : ExprEmpty();
20327 // [Clang extension]
20328 // -- If e has the form __builtin_choose_expr(...), the set of potential
20329 // results is the union of the sets of potential results of the
20330 // second and third subexpressions.
20331 case Expr::ChooseExprClass: {
20332 auto *CE = cast<ChooseExpr>(E);
20334 ExprResult LHS = Rebuild(CE->getLHS());
20335 if (LHS.isInvalid())
20336 return ExprError();
20338 ExprResult RHS = Rebuild(CE->getLHS());
20339 if (RHS.isInvalid())
20340 return ExprError();
20342 if (!LHS.get() && !RHS.get())
20343 return ExprEmpty();
20344 if (!LHS.isUsable())
20345 LHS = CE->getLHS();
20346 if (!RHS.isUsable())
20347 RHS = CE->getRHS();
20349 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
20350 RHS.get(), CE->getRParenLoc());
20353 // Step through non-syntactic nodes.
20354 case Expr::ConstantExprClass: {
20355 auto *CE = cast<ConstantExpr>(E);
20356 ExprResult Sub = Rebuild(CE->getSubExpr());
20357 if (!Sub.isUsable())
20358 return Sub;
20359 return ConstantExpr::Create(S.Context, Sub.get());
20362 // We could mostly rely on the recursive rebuilding to rebuild implicit
20363 // casts, but not at the top level, so rebuild them here.
20364 case Expr::ImplicitCastExprClass: {
20365 auto *ICE = cast<ImplicitCastExpr>(E);
20366 // Only step through the narrow set of cast kinds we expect to encounter.
20367 // Anything else suggests we've left the region in which potential results
20368 // can be found.
20369 switch (ICE->getCastKind()) {
20370 case CK_NoOp:
20371 case CK_DerivedToBase:
20372 case CK_UncheckedDerivedToBase: {
20373 ExprResult Sub = Rebuild(ICE->getSubExpr());
20374 if (!Sub.isUsable())
20375 return Sub;
20376 CXXCastPath Path(ICE->path());
20377 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
20378 ICE->getValueKind(), &Path);
20381 default:
20382 break;
20384 break;
20387 default:
20388 break;
20391 // Can't traverse through this node. Nothing to do.
20392 return ExprEmpty();
20395 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
20396 // Check whether the operand is or contains an object of non-trivial C union
20397 // type.
20398 if (E->getType().isVolatileQualified() &&
20399 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
20400 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
20401 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
20402 Sema::NTCUC_LValueToRValueVolatile,
20403 NTCUK_Destruct|NTCUK_Copy);
20405 // C++2a [basic.def.odr]p4:
20406 // [...] an expression of non-volatile-qualified non-class type to which
20407 // the lvalue-to-rvalue conversion is applied [...]
20408 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
20409 return E;
20411 ExprResult Result =
20412 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
20413 if (Result.isInvalid())
20414 return ExprError();
20415 return Result.get() ? Result : E;
20418 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
20419 Res = CorrectDelayedTyposInExpr(Res);
20421 if (!Res.isUsable())
20422 return Res;
20424 // If a constant-expression is a reference to a variable where we delay
20425 // deciding whether it is an odr-use, just assume we will apply the
20426 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20427 // (a non-type template argument), we have special handling anyway.
20428 return CheckLValueToRValueConversionOperand(Res.get());
20431 void Sema::CleanupVarDeclMarking() {
20432 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20433 // call.
20434 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20435 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
20437 for (Expr *E : LocalMaybeODRUseExprs) {
20438 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
20439 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
20440 DRE->getLocation(), *this);
20441 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
20442 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
20443 *this);
20444 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
20445 for (VarDecl *VD : *FP)
20446 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
20447 } else {
20448 llvm_unreachable("Unexpected expression");
20452 assert(MaybeODRUseExprs.empty() &&
20453 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20456 static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc,
20457 ValueDecl *Var, Expr *E) {
20458 VarDecl *VD = Var->getPotentiallyDecomposedVarDecl();
20459 if (!VD)
20460 return;
20462 const bool RefersToEnclosingScope =
20463 (SemaRef.CurContext != VD->getDeclContext() &&
20464 VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage());
20465 if (RefersToEnclosingScope) {
20466 LambdaScopeInfo *const LSI =
20467 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20468 if (LSI && (!LSI->CallOperator ||
20469 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
20470 // If a variable could potentially be odr-used, defer marking it so
20471 // until we finish analyzing the full expression for any
20472 // lvalue-to-rvalue
20473 // or discarded value conversions that would obviate odr-use.
20474 // Add it to the list of potential captures that will be analyzed
20475 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20476 // unless the variable is a reference that was initialized by a constant
20477 // expression (this will never need to be captured or odr-used).
20479 // FIXME: We can simplify this a lot after implementing P0588R1.
20480 assert(E && "Capture variable should be used in an expression.");
20481 if (!Var->getType()->isReferenceType() ||
20482 !VD->isUsableInConstantExpressions(SemaRef.Context))
20483 LSI->addPotentialCapture(E->IgnoreParens());
20488 static void DoMarkVarDeclReferenced(
20489 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20490 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20491 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20492 isa<FunctionParmPackExpr>(E)) &&
20493 "Invalid Expr argument to DoMarkVarDeclReferenced");
20494 Var->setReferenced();
20496 if (Var->isInvalidDecl())
20497 return;
20499 auto *MSI = Var->getMemberSpecializationInfo();
20500 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20501 : Var->getTemplateSpecializationKind();
20503 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20504 bool UsableInConstantExpr =
20505 Var->mightBeUsableInConstantExpressions(SemaRef.Context);
20507 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
20508 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
20511 // C++20 [expr.const]p12:
20512 // A variable [...] is needed for constant evaluation if it is [...] a
20513 // variable whose name appears as a potentially constant evaluated
20514 // expression that is either a contexpr variable or is of non-volatile
20515 // const-qualified integral type or of reference type
20516 bool NeededForConstantEvaluation =
20517 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20519 bool NeedDefinition =
20520 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
20522 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
20523 "Can't instantiate a partial template specialization.");
20525 // If this might be a member specialization of a static data member, check
20526 // the specialization is visible. We already did the checks for variable
20527 // template specializations when we created them.
20528 if (NeedDefinition && TSK != TSK_Undeclared &&
20529 !isa<VarTemplateSpecializationDecl>(Var))
20530 SemaRef.checkSpecializationVisibility(Loc, Var);
20532 // Perform implicit instantiation of static data members, static data member
20533 // templates of class templates, and variable template specializations. Delay
20534 // instantiations of variable templates, except for those that could be used
20535 // in a constant expression.
20536 if (NeedDefinition && isTemplateInstantiation(TSK)) {
20537 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20538 // instantiation declaration if a variable is usable in a constant
20539 // expression (among other cases).
20540 bool TryInstantiating =
20541 TSK == TSK_ImplicitInstantiation ||
20542 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20544 if (TryInstantiating) {
20545 SourceLocation PointOfInstantiation =
20546 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20547 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20548 if (FirstInstantiation) {
20549 PointOfInstantiation = Loc;
20550 if (MSI)
20551 MSI->setPointOfInstantiation(PointOfInstantiation);
20552 // FIXME: Notify listener.
20553 else
20554 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20557 if (UsableInConstantExpr) {
20558 // Do not defer instantiations of variables that could be used in a
20559 // constant expression.
20560 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
20561 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20564 // Re-set the member to trigger a recomputation of the dependence bits
20565 // for the expression.
20566 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20567 DRE->setDecl(DRE->getDecl());
20568 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
20569 ME->setMemberDecl(ME->getMemberDecl());
20570 } else if (FirstInstantiation) {
20571 SemaRef.PendingInstantiations
20572 .push_back(std::make_pair(Var, PointOfInstantiation));
20573 } else {
20574 bool Inserted = false;
20575 for (auto &I : SemaRef.SavedPendingInstantiations) {
20576 auto Iter = llvm::find_if(
20577 I, [Var](const Sema::PendingImplicitInstantiation &P) {
20578 return P.first == Var;
20580 if (Iter != I.end()) {
20581 SemaRef.PendingInstantiations.push_back(*Iter);
20582 I.erase(Iter);
20583 Inserted = true;
20584 break;
20588 // FIXME: For a specialization of a variable template, we don't
20589 // distinguish between "declaration and type implicitly instantiated"
20590 // and "implicit instantiation of definition requested", so we have
20591 // no direct way to avoid enqueueing the pending instantiation
20592 // multiple times.
20593 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
20594 SemaRef.PendingInstantiations
20595 .push_back(std::make_pair(Var, PointOfInstantiation));
20600 // C++2a [basic.def.odr]p4:
20601 // A variable x whose name appears as a potentially-evaluated expression e
20602 // is odr-used by e unless
20603 // -- x is a reference that is usable in constant expressions
20604 // -- x is a variable of non-reference type that is usable in constant
20605 // expressions and has no mutable subobjects [FIXME], and e is an
20606 // element of the set of potential results of an expression of
20607 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20608 // conversion is applied
20609 // -- x is a variable of non-reference type, and e is an element of the set
20610 // of potential results of a discarded-value expression to which the
20611 // lvalue-to-rvalue conversion is not applied [FIXME]
20613 // We check the first part of the second bullet here, and
20614 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20615 // FIXME: To get the third bullet right, we need to delay this even for
20616 // variables that are not usable in constant expressions.
20618 // If we already know this isn't an odr-use, there's nothing more to do.
20619 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20620 if (DRE->isNonOdrUse())
20621 return;
20622 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
20623 if (ME->isNonOdrUse())
20624 return;
20626 switch (OdrUse) {
20627 case OdrUseContext::None:
20628 // In some cases, a variable may not have been marked unevaluated, if it
20629 // appears in a defaukt initializer.
20630 assert((!E || isa<FunctionParmPackExpr>(E) ||
20631 SemaRef.isUnevaluatedContext()) &&
20632 "missing non-odr-use marking for unevaluated decl ref");
20633 break;
20635 case OdrUseContext::FormallyOdrUsed:
20636 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20637 // behavior.
20638 break;
20640 case OdrUseContext::Used:
20641 // If we might later find that this expression isn't actually an odr-use,
20642 // delay the marking.
20643 if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
20644 SemaRef.MaybeODRUseExprs.insert(E);
20645 else
20646 MarkVarDeclODRUsed(Var, Loc, SemaRef);
20647 break;
20649 case OdrUseContext::Dependent:
20650 // If this is a dependent context, we don't need to mark variables as
20651 // odr-used, but we may still need to track them for lambda capture.
20652 // FIXME: Do we also need to do this inside dependent typeid expressions
20653 // (which are modeled as unevaluated at this point)?
20654 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20655 break;
20659 static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc,
20660 BindingDecl *BD, Expr *E) {
20661 BD->setReferenced();
20663 if (BD->isInvalidDecl())
20664 return;
20666 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20667 if (OdrUse == OdrUseContext::Used) {
20668 QualType CaptureType, DeclRefType;
20669 SemaRef.tryCaptureVariable(BD, Loc, Sema::TryCapture_Implicit,
20670 /*EllipsisLoc*/ SourceLocation(),
20671 /*BuildAndDiagnose*/ true, CaptureType,
20672 DeclRefType,
20673 /*FunctionScopeIndexToStopAt*/ nullptr);
20674 } else if (OdrUse == OdrUseContext::Dependent) {
20675 DoMarkPotentialCapture(SemaRef, Loc, BD, E);
20679 /// Mark a variable referenced, and check whether it is odr-used
20680 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
20681 /// used directly for normal expressions referring to VarDecl.
20682 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
20683 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
20686 // C++ [temp.dep.expr]p3:
20687 // An id-expression is type-dependent if it contains:
20688 // - an identifier associated by name lookup with an entity captured by copy
20689 // in a lambda-expression that has an explicit object parameter whose type
20690 // is dependent ([dcl.fct]),
20691 static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(
20692 Sema &SemaRef, ValueDecl *D, Expr *E) {
20693 auto *ID = dyn_cast<DeclRefExpr>(E);
20694 if (!ID || ID->isTypeDependent())
20695 return;
20697 auto IsDependent = [&]() {
20698 const LambdaScopeInfo *LSI = SemaRef.getCurLambda();
20699 if (!LSI)
20700 return false;
20701 if (!LSI->ExplicitObjectParameter ||
20702 !LSI->ExplicitObjectParameter->getType()->isDependentType())
20703 return false;
20704 if (!LSI->CaptureMap.count(D))
20705 return false;
20706 const Capture &Cap = LSI->getCapture(D);
20707 return !Cap.isCopyCapture();
20708 }();
20710 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
20711 IsDependent, SemaRef.getASTContext());
20714 static void
20715 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
20716 bool MightBeOdrUse,
20717 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20718 if (SemaRef.isInOpenMPDeclareTargetContext())
20719 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
20721 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
20722 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
20723 if (SemaRef.getLangOpts().CPlusPlus)
20724 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
20725 Var, E);
20726 return;
20729 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
20730 DoMarkBindingDeclReferenced(SemaRef, Loc, Decl, E);
20731 if (SemaRef.getLangOpts().CPlusPlus)
20732 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
20733 Decl, E);
20734 return;
20736 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20738 // If this is a call to a method via a cast, also mark the method in the
20739 // derived class used in case codegen can devirtualize the call.
20740 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
20741 if (!ME)
20742 return;
20743 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
20744 if (!MD)
20745 return;
20746 // Only attempt to devirtualize if this is truly a virtual call.
20747 bool IsVirtualCall = MD->isVirtual() &&
20748 ME->performsVirtualDispatch(SemaRef.getLangOpts());
20749 if (!IsVirtualCall)
20750 return;
20752 // If it's possible to devirtualize the call, mark the called function
20753 // referenced.
20754 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
20755 ME->getBase(), SemaRef.getLangOpts().AppleKext);
20756 if (DM)
20757 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20760 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
20762 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be
20763 /// handled with care if the DeclRefExpr is not newly-created.
20764 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
20765 // TODO: update this with DR# once a defect report is filed.
20766 // C++11 defect. The address of a pure member should not be an ODR use, even
20767 // if it's a qualified reference.
20768 bool OdrUse = true;
20769 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
20770 if (Method->isVirtual() &&
20771 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
20772 OdrUse = false;
20774 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
20775 if (!isUnevaluatedContext() && !isConstantEvaluatedContext() &&
20776 !isImmediateFunctionContext() &&
20777 !isCheckingDefaultArgumentOrInitializer() &&
20778 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20779 !FD->isDependentContext())
20780 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
20782 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20783 RefsMinusAssignments);
20786 /// Perform reference-marking and odr-use handling for a MemberExpr.
20787 void Sema::MarkMemberReferenced(MemberExpr *E) {
20788 // C++11 [basic.def.odr]p2:
20789 // A non-overloaded function whose name appears as a potentially-evaluated
20790 // expression or a member of a set of candidate functions, if selected by
20791 // overload resolution when referred to from a potentially-evaluated
20792 // expression, is odr-used, unless it is a pure virtual function and its
20793 // name is not explicitly qualified.
20794 bool MightBeOdrUse = true;
20795 if (E->performsVirtualDispatch(getLangOpts())) {
20796 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20797 if (Method->isPure())
20798 MightBeOdrUse = false;
20800 SourceLocation Loc =
20801 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20802 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20803 RefsMinusAssignments);
20806 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
20807 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
20808 for (VarDecl *VD : *E)
20809 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
20810 RefsMinusAssignments);
20813 /// Perform marking for a reference to an arbitrary declaration. It
20814 /// marks the declaration referenced, and performs odr-use checking for
20815 /// functions and variables. This method should not be used when building a
20816 /// normal expression which refers to a variable.
20817 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
20818 bool MightBeOdrUse) {
20819 if (MightBeOdrUse) {
20820 if (auto *VD = dyn_cast<VarDecl>(D)) {
20821 MarkVariableReferenced(Loc, VD);
20822 return;
20825 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20826 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
20827 return;
20829 D->setReferenced();
20832 namespace {
20833 // Mark all of the declarations used by a type as referenced.
20834 // FIXME: Not fully implemented yet! We need to have a better understanding
20835 // of when we're entering a context we should not recurse into.
20836 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20837 // TreeTransforms rebuilding the type in a new context. Rather than
20838 // duplicating the TreeTransform logic, we should consider reusing it here.
20839 // Currently that causes problems when rebuilding LambdaExprs.
20840 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
20841 Sema &S;
20842 SourceLocation Loc;
20844 public:
20845 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
20847 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
20849 bool TraverseTemplateArgument(const TemplateArgument &Arg);
20853 bool MarkReferencedDecls::TraverseTemplateArgument(
20854 const TemplateArgument &Arg) {
20856 // A non-type template argument is a constant-evaluated context.
20857 EnterExpressionEvaluationContext Evaluated(
20858 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
20859 if (Arg.getKind() == TemplateArgument::Declaration) {
20860 if (Decl *D = Arg.getAsDecl())
20861 S.MarkAnyDeclReferenced(Loc, D, true);
20862 } else if (Arg.getKind() == TemplateArgument::Expression) {
20863 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
20867 return Inherited::TraverseTemplateArgument(Arg);
20870 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
20871 MarkReferencedDecls Marker(*this, Loc);
20872 Marker.TraverseType(T);
20875 namespace {
20876 /// Helper class that marks all of the declarations referenced by
20877 /// potentially-evaluated subexpressions as "referenced".
20878 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20879 public:
20880 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20881 bool SkipLocalVariables;
20882 ArrayRef<const Expr *> StopAt;
20884 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20885 ArrayRef<const Expr *> StopAt)
20886 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20888 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20889 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
20892 void Visit(Expr *E) {
20893 if (llvm::is_contained(StopAt, E))
20894 return;
20895 Inherited::Visit(E);
20898 void VisitConstantExpr(ConstantExpr *E) {
20899 // Don't mark declarations within a ConstantExpression, as this expression
20900 // will be evaluated and folded to a value.
20903 void VisitDeclRefExpr(DeclRefExpr *E) {
20904 // If we were asked not to visit local variables, don't.
20905 if (SkipLocalVariables) {
20906 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
20907 if (VD->hasLocalStorage())
20908 return;
20911 // FIXME: This can trigger the instantiation of the initializer of a
20912 // variable, which can cause the expression to become value-dependent
20913 // or error-dependent. Do we need to propagate the new dependence bits?
20914 S.MarkDeclRefReferenced(E);
20917 void VisitMemberExpr(MemberExpr *E) {
20918 S.MarkMemberReferenced(E);
20919 Visit(E->getBase());
20922 } // namespace
20924 /// Mark any declarations that appear within this expression or any
20925 /// potentially-evaluated subexpressions as "referenced".
20927 /// \param SkipLocalVariables If true, don't mark local variables as
20928 /// 'referenced'.
20929 /// \param StopAt Subexpressions that we shouldn't recurse into.
20930 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
20931 bool SkipLocalVariables,
20932 ArrayRef<const Expr*> StopAt) {
20933 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20936 /// Emit a diagnostic when statements are reachable.
20937 /// FIXME: check for reachability even in expressions for which we don't build a
20938 /// CFG (eg, in the initializer of a global or in a constant expression).
20939 /// For example,
20940 /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
20941 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
20942 const PartialDiagnostic &PD) {
20943 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
20944 if (!FunctionScopes.empty())
20945 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20946 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
20947 return true;
20950 // The initializer of a constexpr variable or of the first declaration of a
20951 // static data member is not syntactically a constant evaluated constant,
20952 // but nonetheless is always required to be a constant expression, so we
20953 // can skip diagnosing.
20954 // FIXME: Using the mangling context here is a hack.
20955 if (auto *VD = dyn_cast_or_null<VarDecl>(
20956 ExprEvalContexts.back().ManglingContextDecl)) {
20957 if (VD->isConstexpr() ||
20958 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
20959 return false;
20960 // FIXME: For any other kind of variable, we should build a CFG for its
20961 // initializer and check whether the context in question is reachable.
20964 Diag(Loc, PD);
20965 return true;
20968 /// Emit a diagnostic that describes an effect on the run-time behavior
20969 /// of the program being compiled.
20971 /// This routine emits the given diagnostic when the code currently being
20972 /// type-checked is "potentially evaluated", meaning that there is a
20973 /// possibility that the code will actually be executable. Code in sizeof()
20974 /// expressions, code used only during overload resolution, etc., are not
20975 /// potentially evaluated. This routine will suppress such diagnostics or,
20976 /// in the absolutely nutty case of potentially potentially evaluated
20977 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
20978 /// later.
20980 /// This routine should be used for all diagnostics that describe the run-time
20981 /// behavior of a program, such as passing a non-POD value through an ellipsis.
20982 /// Failure to do so will likely result in spurious diagnostics or failures
20983 /// during overload resolution or within sizeof/alignof/typeof/typeid.
20984 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
20985 const PartialDiagnostic &PD) {
20987 if (ExprEvalContexts.back().isDiscardedStatementContext())
20988 return false;
20990 switch (ExprEvalContexts.back().Context) {
20991 case ExpressionEvaluationContext::Unevaluated:
20992 case ExpressionEvaluationContext::UnevaluatedList:
20993 case ExpressionEvaluationContext::UnevaluatedAbstract:
20994 case ExpressionEvaluationContext::DiscardedStatement:
20995 // The argument will never be evaluated, so don't complain.
20996 break;
20998 case ExpressionEvaluationContext::ConstantEvaluated:
20999 case ExpressionEvaluationContext::ImmediateFunctionContext:
21000 // Relevant diagnostics should be produced by constant evaluation.
21001 break;
21003 case ExpressionEvaluationContext::PotentiallyEvaluated:
21004 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
21005 return DiagIfReachable(Loc, Stmts, PD);
21008 return false;
21011 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
21012 const PartialDiagnostic &PD) {
21013 return DiagRuntimeBehavior(
21014 Loc, Statement ? llvm::ArrayRef(Statement) : std::nullopt, PD);
21017 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
21018 CallExpr *CE, FunctionDecl *FD) {
21019 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
21020 return false;
21022 // If we're inside a decltype's expression, don't check for a valid return
21023 // type or construct temporaries until we know whether this is the last call.
21024 if (ExprEvalContexts.back().ExprContext ==
21025 ExpressionEvaluationContextRecord::EK_Decltype) {
21026 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
21027 return false;
21030 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
21031 FunctionDecl *FD;
21032 CallExpr *CE;
21034 public:
21035 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
21036 : FD(FD), CE(CE) { }
21038 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
21039 if (!FD) {
21040 S.Diag(Loc, diag::err_call_incomplete_return)
21041 << T << CE->getSourceRange();
21042 return;
21045 S.Diag(Loc, diag::err_call_function_incomplete_return)
21046 << CE->getSourceRange() << FD << T;
21047 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
21048 << FD->getDeclName();
21050 } Diagnoser(FD, CE);
21052 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
21053 return true;
21055 return false;
21058 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
21059 // will prevent this condition from triggering, which is what we want.
21060 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
21061 SourceLocation Loc;
21063 unsigned diagnostic = diag::warn_condition_is_assignment;
21064 bool IsOrAssign = false;
21066 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
21067 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
21068 return;
21070 IsOrAssign = Op->getOpcode() == BO_OrAssign;
21072 // Greylist some idioms by putting them into a warning subcategory.
21073 if (ObjCMessageExpr *ME
21074 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
21075 Selector Sel = ME->getSelector();
21077 // self = [<foo> init...]
21078 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
21079 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21081 // <foo> = [<bar> nextObject]
21082 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
21083 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21086 Loc = Op->getOperatorLoc();
21087 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
21088 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
21089 return;
21091 IsOrAssign = Op->getOperator() == OO_PipeEqual;
21092 Loc = Op->getOperatorLoc();
21093 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
21094 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
21095 else {
21096 // Not an assignment.
21097 return;
21100 Diag(Loc, diagnostic) << E->getSourceRange();
21102 SourceLocation Open = E->getBeginLoc();
21103 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
21104 Diag(Loc, diag::note_condition_assign_silence)
21105 << FixItHint::CreateInsertion(Open, "(")
21106 << FixItHint::CreateInsertion(Close, ")");
21108 if (IsOrAssign)
21109 Diag(Loc, diag::note_condition_or_assign_to_comparison)
21110 << FixItHint::CreateReplacement(Loc, "!=");
21111 else
21112 Diag(Loc, diag::note_condition_assign_to_comparison)
21113 << FixItHint::CreateReplacement(Loc, "==");
21116 /// Redundant parentheses over an equality comparison can indicate
21117 /// that the user intended an assignment used as condition.
21118 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
21119 // Don't warn if the parens came from a macro.
21120 SourceLocation parenLoc = ParenE->getBeginLoc();
21121 if (parenLoc.isInvalid() || parenLoc.isMacroID())
21122 return;
21123 // Don't warn for dependent expressions.
21124 if (ParenE->isTypeDependent())
21125 return;
21127 Expr *E = ParenE->IgnoreParens();
21129 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
21130 if (opE->getOpcode() == BO_EQ &&
21131 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
21132 == Expr::MLV_Valid) {
21133 SourceLocation Loc = opE->getOperatorLoc();
21135 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
21136 SourceRange ParenERange = ParenE->getSourceRange();
21137 Diag(Loc, diag::note_equality_comparison_silence)
21138 << FixItHint::CreateRemoval(ParenERange.getBegin())
21139 << FixItHint::CreateRemoval(ParenERange.getEnd());
21140 Diag(Loc, diag::note_equality_comparison_to_assign)
21141 << FixItHint::CreateReplacement(Loc, "=");
21145 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
21146 bool IsConstexpr) {
21147 DiagnoseAssignmentAsCondition(E);
21148 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
21149 DiagnoseEqualityWithExtraParens(parenE);
21151 ExprResult result = CheckPlaceholderExpr(E);
21152 if (result.isInvalid()) return ExprError();
21153 E = result.get();
21155 if (!E->isTypeDependent()) {
21156 if (getLangOpts().CPlusPlus)
21157 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
21159 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
21160 if (ERes.isInvalid())
21161 return ExprError();
21162 E = ERes.get();
21164 QualType T = E->getType();
21165 if (!T->isScalarType()) { // C99 6.8.4.1p1
21166 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
21167 << T << E->getSourceRange();
21168 return ExprError();
21170 CheckBoolLikeConversion(E, Loc);
21173 return E;
21176 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
21177 Expr *SubExpr, ConditionKind CK,
21178 bool MissingOK) {
21179 // MissingOK indicates whether having no condition expression is valid
21180 // (for loop) or invalid (e.g. while loop).
21181 if (!SubExpr)
21182 return MissingOK ? ConditionResult() : ConditionError();
21184 ExprResult Cond;
21185 switch (CK) {
21186 case ConditionKind::Boolean:
21187 Cond = CheckBooleanCondition(Loc, SubExpr);
21188 break;
21190 case ConditionKind::ConstexprIf:
21191 Cond = CheckBooleanCondition(Loc, SubExpr, true);
21192 break;
21194 case ConditionKind::Switch:
21195 Cond = CheckSwitchCondition(Loc, SubExpr);
21196 break;
21198 if (Cond.isInvalid()) {
21199 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
21200 {SubExpr}, PreferredConditionType(CK));
21201 if (!Cond.get())
21202 return ConditionError();
21204 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
21205 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
21206 if (!FullExpr.get())
21207 return ConditionError();
21209 return ConditionResult(*this, nullptr, FullExpr,
21210 CK == ConditionKind::ConstexprIf);
21213 namespace {
21214 /// A visitor for rebuilding a call to an __unknown_any expression
21215 /// to have an appropriate type.
21216 struct RebuildUnknownAnyFunction
21217 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
21219 Sema &S;
21221 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21223 ExprResult VisitStmt(Stmt *S) {
21224 llvm_unreachable("unexpected statement!");
21227 ExprResult VisitExpr(Expr *E) {
21228 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
21229 << E->getSourceRange();
21230 return ExprError();
21233 /// Rebuild an expression which simply semantically wraps another
21234 /// expression which it shares the type and value kind of.
21235 template <class T> ExprResult rebuildSugarExpr(T *E) {
21236 ExprResult SubResult = Visit(E->getSubExpr());
21237 if (SubResult.isInvalid()) return ExprError();
21239 Expr *SubExpr = SubResult.get();
21240 E->setSubExpr(SubExpr);
21241 E->setType(SubExpr->getType());
21242 E->setValueKind(SubExpr->getValueKind());
21243 assert(E->getObjectKind() == OK_Ordinary);
21244 return E;
21247 ExprResult VisitParenExpr(ParenExpr *E) {
21248 return rebuildSugarExpr(E);
21251 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21252 return rebuildSugarExpr(E);
21255 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21256 ExprResult SubResult = Visit(E->getSubExpr());
21257 if (SubResult.isInvalid()) return ExprError();
21259 Expr *SubExpr = SubResult.get();
21260 E->setSubExpr(SubExpr);
21261 E->setType(S.Context.getPointerType(SubExpr->getType()));
21262 assert(E->isPRValue());
21263 assert(E->getObjectKind() == OK_Ordinary);
21264 return E;
21267 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21268 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
21270 E->setType(VD->getType());
21272 assert(E->isPRValue());
21273 if (S.getLangOpts().CPlusPlus &&
21274 !(isa<CXXMethodDecl>(VD) &&
21275 cast<CXXMethodDecl>(VD)->isInstance()))
21276 E->setValueKind(VK_LValue);
21278 return E;
21281 ExprResult VisitMemberExpr(MemberExpr *E) {
21282 return resolveDecl(E, E->getMemberDecl());
21285 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21286 return resolveDecl(E, E->getDecl());
21291 /// Given a function expression of unknown-any type, try to rebuild it
21292 /// to have a function type.
21293 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
21294 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
21295 if (Result.isInvalid()) return ExprError();
21296 return S.DefaultFunctionArrayConversion(Result.get());
21299 namespace {
21300 /// A visitor for rebuilding an expression of type __unknown_anytype
21301 /// into one which resolves the type directly on the referring
21302 /// expression. Strict preservation of the original source
21303 /// structure is not a goal.
21304 struct RebuildUnknownAnyExpr
21305 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21307 Sema &S;
21309 /// The current destination type.
21310 QualType DestType;
21312 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21313 : S(S), DestType(CastType) {}
21315 ExprResult VisitStmt(Stmt *S) {
21316 llvm_unreachable("unexpected statement!");
21319 ExprResult VisitExpr(Expr *E) {
21320 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21321 << E->getSourceRange();
21322 return ExprError();
21325 ExprResult VisitCallExpr(CallExpr *E);
21326 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21328 /// Rebuild an expression which simply semantically wraps another
21329 /// expression which it shares the type and value kind of.
21330 template <class T> ExprResult rebuildSugarExpr(T *E) {
21331 ExprResult SubResult = Visit(E->getSubExpr());
21332 if (SubResult.isInvalid()) return ExprError();
21333 Expr *SubExpr = SubResult.get();
21334 E->setSubExpr(SubExpr);
21335 E->setType(SubExpr->getType());
21336 E->setValueKind(SubExpr->getValueKind());
21337 assert(E->getObjectKind() == OK_Ordinary);
21338 return E;
21341 ExprResult VisitParenExpr(ParenExpr *E) {
21342 return rebuildSugarExpr(E);
21345 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21346 return rebuildSugarExpr(E);
21349 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21350 const PointerType *Ptr = DestType->getAs<PointerType>();
21351 if (!Ptr) {
21352 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
21353 << E->getSourceRange();
21354 return ExprError();
21357 if (isa<CallExpr>(E->getSubExpr())) {
21358 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
21359 << E->getSourceRange();
21360 return ExprError();
21363 assert(E->isPRValue());
21364 assert(E->getObjectKind() == OK_Ordinary);
21365 E->setType(DestType);
21367 // Build the sub-expression as if it were an object of the pointee type.
21368 DestType = Ptr->getPointeeType();
21369 ExprResult SubResult = Visit(E->getSubExpr());
21370 if (SubResult.isInvalid()) return ExprError();
21371 E->setSubExpr(SubResult.get());
21372 return E;
21375 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21377 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21379 ExprResult VisitMemberExpr(MemberExpr *E) {
21380 return resolveDecl(E, E->getMemberDecl());
21383 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21384 return resolveDecl(E, E->getDecl());
21389 /// Rebuilds a call expression which yielded __unknown_anytype.
21390 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21391 Expr *CalleeExpr = E->getCallee();
21393 enum FnKind {
21394 FK_MemberFunction,
21395 FK_FunctionPointer,
21396 FK_BlockPointer
21399 FnKind Kind;
21400 QualType CalleeType = CalleeExpr->getType();
21401 if (CalleeType == S.Context.BoundMemberTy) {
21402 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
21403 Kind = FK_MemberFunction;
21404 CalleeType = Expr::findBoundMemberType(CalleeExpr);
21405 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21406 CalleeType = Ptr->getPointeeType();
21407 Kind = FK_FunctionPointer;
21408 } else {
21409 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21410 Kind = FK_BlockPointer;
21412 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21414 // Verify that this is a legal result type of a function.
21415 if (DestType->isArrayType() || DestType->isFunctionType()) {
21416 unsigned diagID = diag::err_func_returning_array_function;
21417 if (Kind == FK_BlockPointer)
21418 diagID = diag::err_block_returning_array_function;
21420 S.Diag(E->getExprLoc(), diagID)
21421 << DestType->isFunctionType() << DestType;
21422 return ExprError();
21425 // Otherwise, go ahead and set DestType as the call's result.
21426 E->setType(DestType.getNonLValueExprType(S.Context));
21427 E->setValueKind(Expr::getValueKindForType(DestType));
21428 assert(E->getObjectKind() == OK_Ordinary);
21430 // Rebuild the function type, replacing the result type with DestType.
21431 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
21432 if (Proto) {
21433 // __unknown_anytype(...) is a special case used by the debugger when
21434 // it has no idea what a function's signature is.
21436 // We want to build this call essentially under the K&R
21437 // unprototyped rules, but making a FunctionNoProtoType in C++
21438 // would foul up all sorts of assumptions. However, we cannot
21439 // simply pass all arguments as variadic arguments, nor can we
21440 // portably just call the function under a non-variadic type; see
21441 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21442 // However, it turns out that in practice it is generally safe to
21443 // call a function declared as "A foo(B,C,D);" under the prototype
21444 // "A foo(B,C,D,...);". The only known exception is with the
21445 // Windows ABI, where any variadic function is implicitly cdecl
21446 // regardless of its normal CC. Therefore we change the parameter
21447 // types to match the types of the arguments.
21449 // This is a hack, but it is far superior to moving the
21450 // corresponding target-specific code from IR-gen to Sema/AST.
21452 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21453 SmallVector<QualType, 8> ArgTypes;
21454 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21455 ArgTypes.reserve(E->getNumArgs());
21456 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21457 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
21459 ParamTypes = ArgTypes;
21461 DestType = S.Context.getFunctionType(DestType, ParamTypes,
21462 Proto->getExtProtoInfo());
21463 } else {
21464 DestType = S.Context.getFunctionNoProtoType(DestType,
21465 FnType->getExtInfo());
21468 // Rebuild the appropriate pointer-to-function type.
21469 switch (Kind) {
21470 case FK_MemberFunction:
21471 // Nothing to do.
21472 break;
21474 case FK_FunctionPointer:
21475 DestType = S.Context.getPointerType(DestType);
21476 break;
21478 case FK_BlockPointer:
21479 DestType = S.Context.getBlockPointerType(DestType);
21480 break;
21483 // Finally, we can recurse.
21484 ExprResult CalleeResult = Visit(CalleeExpr);
21485 if (!CalleeResult.isUsable()) return ExprError();
21486 E->setCallee(CalleeResult.get());
21488 // Bind a temporary if necessary.
21489 return S.MaybeBindToTemporary(E);
21492 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21493 // Verify that this is a legal result type of a call.
21494 if (DestType->isArrayType() || DestType->isFunctionType()) {
21495 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
21496 << DestType->isFunctionType() << DestType;
21497 return ExprError();
21500 // Rewrite the method result type if available.
21501 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21502 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21503 Method->setReturnType(DestType);
21506 // Change the type of the message.
21507 E->setType(DestType.getNonReferenceType());
21508 E->setValueKind(Expr::getValueKindForType(DestType));
21510 return S.MaybeBindToTemporary(E);
21513 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21514 // The only case we should ever see here is a function-to-pointer decay.
21515 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21516 assert(E->isPRValue());
21517 assert(E->getObjectKind() == OK_Ordinary);
21519 E->setType(DestType);
21521 // Rebuild the sub-expression as the pointee (function) type.
21522 DestType = DestType->castAs<PointerType>()->getPointeeType();
21524 ExprResult Result = Visit(E->getSubExpr());
21525 if (!Result.isUsable()) return ExprError();
21527 E->setSubExpr(Result.get());
21528 return E;
21529 } else if (E->getCastKind() == CK_LValueToRValue) {
21530 assert(E->isPRValue());
21531 assert(E->getObjectKind() == OK_Ordinary);
21533 assert(isa<BlockPointerType>(E->getType()));
21535 E->setType(DestType);
21537 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21538 DestType = S.Context.getLValueReferenceType(DestType);
21540 ExprResult Result = Visit(E->getSubExpr());
21541 if (!Result.isUsable()) return ExprError();
21543 E->setSubExpr(Result.get());
21544 return E;
21545 } else {
21546 llvm_unreachable("Unhandled cast type!");
21550 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21551 ExprValueKind ValueKind = VK_LValue;
21552 QualType Type = DestType;
21554 // We know how to make this work for certain kinds of decls:
21556 // - functions
21557 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
21558 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21559 DestType = Ptr->getPointeeType();
21560 ExprResult Result = resolveDecl(E, VD);
21561 if (Result.isInvalid()) return ExprError();
21562 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
21563 VK_PRValue);
21566 if (!Type->isFunctionType()) {
21567 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
21568 << VD << E->getSourceRange();
21569 return ExprError();
21571 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21572 // We must match the FunctionDecl's type to the hack introduced in
21573 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21574 // type. See the lengthy commentary in that routine.
21575 QualType FDT = FD->getType();
21576 const FunctionType *FnType = FDT->castAs<FunctionType>();
21577 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
21578 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
21579 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21580 SourceLocation Loc = FD->getLocation();
21581 FunctionDecl *NewFD = FunctionDecl::Create(
21582 S.Context, FD->getDeclContext(), Loc, Loc,
21583 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
21584 SC_None, S.getCurFPFeatures().isFPConstrained(),
21585 false /*isInlineSpecified*/, FD->hasPrototype(),
21586 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21588 if (FD->getQualifier())
21589 NewFD->setQualifierInfo(FD->getQualifierLoc());
21591 SmallVector<ParmVarDecl*, 16> Params;
21592 for (const auto &AI : FT->param_types()) {
21593 ParmVarDecl *Param =
21594 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
21595 Param->setScopeInfo(0, Params.size());
21596 Params.push_back(Param);
21598 NewFD->setParams(Params);
21599 DRE->setDecl(NewFD);
21600 VD = DRE->getDecl();
21604 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
21605 if (MD->isInstance()) {
21606 ValueKind = VK_PRValue;
21607 Type = S.Context.BoundMemberTy;
21610 // Function references aren't l-values in C.
21611 if (!S.getLangOpts().CPlusPlus)
21612 ValueKind = VK_PRValue;
21614 // - variables
21615 } else if (isa<VarDecl>(VD)) {
21616 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21617 Type = RefTy->getPointeeType();
21618 } else if (Type->isFunctionType()) {
21619 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
21620 << VD << E->getSourceRange();
21621 return ExprError();
21624 // - nothing else
21625 } else {
21626 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
21627 << VD << E->getSourceRange();
21628 return ExprError();
21631 // Modifying the declaration like this is friendly to IR-gen but
21632 // also really dangerous.
21633 VD->setType(DestType);
21634 E->setType(Type);
21635 E->setValueKind(ValueKind);
21636 return E;
21639 /// Check a cast of an unknown-any type. We intentionally only
21640 /// trigger this for C-style casts.
21641 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
21642 Expr *CastExpr, CastKind &CastKind,
21643 ExprValueKind &VK, CXXCastPath &Path) {
21644 // The type we're casting to must be either void or complete.
21645 if (!CastType->isVoidType() &&
21646 RequireCompleteType(TypeRange.getBegin(), CastType,
21647 diag::err_typecheck_cast_to_incomplete))
21648 return ExprError();
21650 // Rewrite the casted expression from scratch.
21651 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
21652 if (!result.isUsable()) return ExprError();
21654 CastExpr = result.get();
21655 VK = CastExpr->getValueKind();
21656 CastKind = CK_NoOp;
21658 return CastExpr;
21661 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
21662 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
21665 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
21666 Expr *arg, QualType &paramType) {
21667 // If the syntactic form of the argument is not an explicit cast of
21668 // any sort, just do default argument promotion.
21669 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
21670 if (!castArg) {
21671 ExprResult result = DefaultArgumentPromotion(arg);
21672 if (result.isInvalid()) return ExprError();
21673 paramType = result.get()->getType();
21674 return result;
21677 // Otherwise, use the type that was written in the explicit cast.
21678 assert(!arg->hasPlaceholderType());
21679 paramType = castArg->getTypeAsWritten();
21681 // Copy-initialize a parameter of that type.
21682 InitializedEntity entity =
21683 InitializedEntity::InitializeParameter(Context, paramType,
21684 /*consumed*/ false);
21685 return PerformCopyInitialization(entity, callLoc, arg);
21688 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
21689 Expr *orig = E;
21690 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21691 while (true) {
21692 E = E->IgnoreParenImpCasts();
21693 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
21694 E = call->getCallee();
21695 diagID = diag::err_uncasted_call_of_unknown_any;
21696 } else {
21697 break;
21701 SourceLocation loc;
21702 NamedDecl *d;
21703 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
21704 loc = ref->getLocation();
21705 d = ref->getDecl();
21706 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
21707 loc = mem->getMemberLoc();
21708 d = mem->getMemberDecl();
21709 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
21710 diagID = diag::err_uncasted_call_of_unknown_any;
21711 loc = msg->getSelectorStartLoc();
21712 d = msg->getMethodDecl();
21713 if (!d) {
21714 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
21715 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21716 << orig->getSourceRange();
21717 return ExprError();
21719 } else {
21720 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21721 << E->getSourceRange();
21722 return ExprError();
21725 S.Diag(loc, diagID) << d << orig->getSourceRange();
21727 // Never recoverable.
21728 return ExprError();
21731 /// Check for operands with placeholder types and complain if found.
21732 /// Returns ExprError() if there was an error and no recovery was possible.
21733 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
21734 if (!Context.isDependenceAllowed()) {
21735 // C cannot handle TypoExpr nodes on either side of a binop because it
21736 // doesn't handle dependent types properly, so make sure any TypoExprs have
21737 // been dealt with before checking the operands.
21738 ExprResult Result = CorrectDelayedTyposInExpr(E);
21739 if (!Result.isUsable()) return ExprError();
21740 E = Result.get();
21743 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21744 if (!placeholderType) return E;
21746 switch (placeholderType->getKind()) {
21748 // Overloaded expressions.
21749 case BuiltinType::Overload: {
21750 // Try to resolve a single function template specialization.
21751 // This is obligatory.
21752 ExprResult Result = E;
21753 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
21754 return Result;
21756 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21757 // leaves Result unchanged on failure.
21758 Result = E;
21759 if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
21760 return Result;
21762 // If that failed, try to recover with a call.
21763 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21764 /*complain*/ true);
21765 return Result;
21768 // Bound member functions.
21769 case BuiltinType::BoundMember: {
21770 ExprResult result = E;
21771 const Expr *BME = E->IgnoreParens();
21772 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21773 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21774 if (isa<CXXPseudoDestructorExpr>(BME)) {
21775 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21776 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
21777 if (ME->getMemberNameInfo().getName().getNameKind() ==
21778 DeclarationName::CXXDestructorName)
21779 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21781 tryToRecoverWithCall(result, PD,
21782 /*complain*/ true);
21783 return result;
21786 // ARC unbridged casts.
21787 case BuiltinType::ARCUnbridgedCast: {
21788 Expr *realCast = stripARCUnbridgedCast(E);
21789 diagnoseARCUnbridgedCast(realCast);
21790 return realCast;
21793 // Expressions of unknown type.
21794 case BuiltinType::UnknownAny:
21795 return diagnoseUnknownAnyExpr(*this, E);
21797 // Pseudo-objects.
21798 case BuiltinType::PseudoObject:
21799 return checkPseudoObjectRValue(E);
21801 case BuiltinType::BuiltinFn: {
21802 // Accept __noop without parens by implicitly converting it to a call expr.
21803 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
21804 if (DRE) {
21805 auto *FD = cast<FunctionDecl>(DRE->getDecl());
21806 unsigned BuiltinID = FD->getBuiltinID();
21807 if (BuiltinID == Builtin::BI__noop) {
21808 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
21809 CK_BuiltinFnToFnPtr)
21810 .get();
21811 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
21812 VK_PRValue, SourceLocation(),
21813 FPOptionsOverride());
21816 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
21817 // Any use of these other than a direct call is ill-formed as of C++20,
21818 // because they are not addressable functions. In earlier language
21819 // modes, warn and force an instantiation of the real body.
21820 Diag(E->getBeginLoc(),
21821 getLangOpts().CPlusPlus20
21822 ? diag::err_use_of_unaddressable_function
21823 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21824 if (FD->isImplicitlyInstantiable()) {
21825 // Require a definition here because a normal attempt at
21826 // instantiation for a builtin will be ignored, and we won't try
21827 // again later. We assume that the definition of the template
21828 // precedes this use.
21829 InstantiateFunctionDefinition(E->getBeginLoc(), FD,
21830 /*Recursive=*/false,
21831 /*DefinitionRequired=*/true,
21832 /*AtEndOfTU=*/false);
21834 // Produce a properly-typed reference to the function.
21835 CXXScopeSpec SS;
21836 SS.Adopt(DRE->getQualifierLoc());
21837 TemplateArgumentListInfo TemplateArgs;
21838 DRE->copyTemplateArgumentsInto(TemplateArgs);
21839 return BuildDeclRefExpr(
21840 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
21841 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
21842 DRE->getTemplateKeywordLoc(),
21843 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21847 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
21848 return ExprError();
21851 case BuiltinType::IncompleteMatrixIdx:
21852 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
21853 ->getRowIdx()
21854 ->getBeginLoc(),
21855 diag::err_matrix_incomplete_index);
21856 return ExprError();
21858 // Expressions of unknown type.
21859 case BuiltinType::OMPArraySection:
21860 Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
21861 return ExprError();
21863 // Expressions of unknown type.
21864 case BuiltinType::OMPArrayShaping:
21865 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
21867 case BuiltinType::OMPIterator:
21868 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
21870 // Everything else should be impossible.
21871 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21872 case BuiltinType::Id:
21873 #include "clang/Basic/OpenCLImageTypes.def"
21874 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21875 case BuiltinType::Id:
21876 #include "clang/Basic/OpenCLExtensionTypes.def"
21877 #define SVE_TYPE(Name, Id, SingletonId) \
21878 case BuiltinType::Id:
21879 #include "clang/Basic/AArch64SVEACLETypes.def"
21880 #define PPC_VECTOR_TYPE(Name, Id, Size) \
21881 case BuiltinType::Id:
21882 #include "clang/Basic/PPCTypes.def"
21883 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21884 #include "clang/Basic/RISCVVTypes.def"
21885 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21886 #include "clang/Basic/WebAssemblyReferenceTypes.def"
21887 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21888 #define PLACEHOLDER_TYPE(Id, SingletonId)
21889 #include "clang/AST/BuiltinTypes.def"
21890 break;
21893 llvm_unreachable("invalid placeholder type!");
21896 bool Sema::CheckCaseExpression(Expr *E) {
21897 if (E->isTypeDependent())
21898 return true;
21899 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
21900 return E->getType()->isIntegralOrEnumerationType();
21901 return false;
21904 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
21905 ExprResult
21906 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
21907 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
21908 "Unknown Objective-C Boolean value!");
21909 QualType BoolT = Context.ObjCBuiltinBoolTy;
21910 if (!Context.getBOOLDecl()) {
21911 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
21912 Sema::LookupOrdinaryName);
21913 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
21914 NamedDecl *ND = Result.getFoundDecl();
21915 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
21916 Context.setBOOLDecl(TD);
21919 if (Context.getBOOLDecl())
21920 BoolT = Context.getBOOLType();
21921 return new (Context)
21922 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
21925 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
21926 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
21927 SourceLocation RParen) {
21928 auto FindSpecVersion =
21929 [&](StringRef Platform) -> std::optional<VersionTuple> {
21930 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
21931 return Spec.getPlatform() == Platform;
21933 // Transcribe the "ios" availability check to "maccatalyst" when compiling
21934 // for "maccatalyst" if "maccatalyst" is not specified.
21935 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
21936 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
21937 return Spec.getPlatform() == "ios";
21940 if (Spec == AvailSpecs.end())
21941 return std::nullopt;
21942 return Spec->getVersion();
21945 VersionTuple Version;
21946 if (auto MaybeVersion =
21947 FindSpecVersion(Context.getTargetInfo().getPlatformName()))
21948 Version = *MaybeVersion;
21950 // The use of `@available` in the enclosing context should be analyzed to
21951 // warn when it's used inappropriately (i.e. not if(@available)).
21952 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
21953 Context->HasPotentialAvailabilityViolations = true;
21955 return new (Context)
21956 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
21959 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
21960 ArrayRef<Expr *> SubExprs, QualType T) {
21961 if (!Context.getLangOpts().RecoveryAST)
21962 return ExprError();
21964 if (isSFINAEContext())
21965 return ExprError();
21967 if (T.isNull() || T->isUndeducedType() ||
21968 !Context.getLangOpts().RecoveryASTType)
21969 // We don't know the concrete type, fallback to dependent type.
21970 T = Context.DependentTy;
21972 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);