[docs] Fix build-docs.sh
[llvm-project.git] / clang / lib / Sema / SemaExpr.cpp
blobb49b7ce45cf4af396ecc3ece4209832bb32cb09f
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/Lex/LiteralSupport.h"
39 #include "clang/Lex/Preprocessor.h"
40 #include "clang/Sema/AnalysisBasedWarnings.h"
41 #include "clang/Sema/DeclSpec.h"
42 #include "clang/Sema/DelayedDiagnostic.h"
43 #include "clang/Sema/Designator.h"
44 #include "clang/Sema/Initialization.h"
45 #include "clang/Sema/Lookup.h"
46 #include "clang/Sema/Overload.h"
47 #include "clang/Sema/ParsedTemplate.h"
48 #include "clang/Sema/Scope.h"
49 #include "clang/Sema/ScopeInfo.h"
50 #include "clang/Sema/SemaFixItUtils.h"
51 #include "clang/Sema/SemaInternal.h"
52 #include "clang/Sema/Template.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include "llvm/ADT/StringExtras.h"
55 #include "llvm/Support/Casting.h"
56 #include "llvm/Support/ConvertUTF.h"
57 #include "llvm/Support/SaveAndRestore.h"
58 #include "llvm/Support/TypeSize.h"
60 using namespace clang;
61 using namespace sema;
63 /// Determine whether the use of this declaration is valid, without
64 /// emitting diagnostics.
65 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
66 // See if this is an auto-typed variable whose initializer we are parsing.
67 if (ParsingInitForAutoVars.count(D))
68 return false;
70 // See if this is a deleted function.
71 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
72 if (FD->isDeleted())
73 return false;
75 // If the function has a deduced return type, and we can't deduce it,
76 // then we can't use it either.
77 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
78 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
79 return false;
81 // See if this is an aligned allocation/deallocation function that is
82 // unavailable.
83 if (TreatUnavailableAsInvalid &&
84 isUnavailableAlignedAllocationFunction(*FD))
85 return false;
88 // See if this function is unavailable.
89 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
90 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
91 return false;
93 if (isa<UnresolvedUsingIfExistsDecl>(D))
94 return false;
96 return true;
99 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
100 // Warn if this is used but marked unused.
101 if (const auto *A = D->getAttr<UnusedAttr>()) {
102 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
103 // should diagnose them.
104 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
105 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
106 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
107 if (DC && !DC->hasAttr<UnusedAttr>())
108 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
113 /// Emit a note explaining that this function is deleted.
114 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
115 assert(Decl && Decl->isDeleted());
117 if (Decl->isDefaulted()) {
118 // If the method was explicitly defaulted, point at that declaration.
119 if (!Decl->isImplicit())
120 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
122 // Try to diagnose why this special member function was implicitly
123 // deleted. This might fail, if that reason no longer applies.
124 DiagnoseDeletedDefaultedFunction(Decl);
125 return;
128 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
129 if (Ctor && Ctor->isInheritingConstructor())
130 return NoteDeletedInheritingConstructor(Ctor);
132 Diag(Decl->getLocation(), diag::note_availability_specified_here)
133 << Decl << 1;
136 /// Determine whether a FunctionDecl was ever declared with an
137 /// explicit storage class.
138 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
139 for (auto *I : D->redecls()) {
140 if (I->getStorageClass() != SC_None)
141 return true;
143 return false;
146 /// Check whether we're in an extern inline function and referring to a
147 /// variable or function with internal linkage (C11 6.7.4p3).
149 /// This is only a warning because we used to silently accept this code, but
150 /// in many cases it will not behave correctly. This is not enabled in C++ mode
151 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
152 /// and so while there may still be user mistakes, most of the time we can't
153 /// prove that there are errors.
154 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
155 const NamedDecl *D,
156 SourceLocation Loc) {
157 // This is disabled under C++; there are too many ways for this to fire in
158 // contexts where the warning is a false positive, or where it is technically
159 // correct but benign.
160 if (S.getLangOpts().CPlusPlus)
161 return;
163 // Check if this is an inlined function or method.
164 FunctionDecl *Current = S.getCurFunctionDecl();
165 if (!Current)
166 return;
167 if (!Current->isInlined())
168 return;
169 if (!Current->isExternallyVisible())
170 return;
172 // Check if the decl has internal linkage.
173 if (D->getFormalLinkage() != InternalLinkage)
174 return;
176 // Downgrade from ExtWarn to Extension if
177 // (1) the supposedly external inline function is in the main file,
178 // and probably won't be included anywhere else.
179 // (2) the thing we're referencing is a pure function.
180 // (3) the thing we're referencing is another inline function.
181 // This last can give us false negatives, but it's better than warning on
182 // wrappers for simple C library functions.
183 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
184 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
185 if (!DowngradeWarning && UsedFn)
186 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
188 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
189 : diag::ext_internal_in_extern_inline)
190 << /*IsVar=*/!UsedFn << D;
192 S.MaybeSuggestAddingStaticToDecl(Current);
194 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
195 << D;
198 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
199 const FunctionDecl *First = Cur->getFirstDecl();
201 // Suggest "static" on the function, if possible.
202 if (!hasAnyExplicitStorageClass(First)) {
203 SourceLocation DeclBegin = First->getSourceRange().getBegin();
204 Diag(DeclBegin, diag::note_convert_inline_to_static)
205 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
209 /// Determine whether the use of this declaration is valid, and
210 /// emit any corresponding diagnostics.
212 /// This routine diagnoses various problems with referencing
213 /// declarations that can occur when using a declaration. For example,
214 /// it might warn if a deprecated or unavailable declaration is being
215 /// used, or produce an error (and return true) if a C++0x deleted
216 /// function is being used.
218 /// \returns true if there was an error (this declaration cannot be
219 /// referenced), false otherwise.
221 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
222 const ObjCInterfaceDecl *UnknownObjCClass,
223 bool ObjCPropertyAccess,
224 bool AvoidPartialAvailabilityChecks,
225 ObjCInterfaceDecl *ClassReceiver) {
226 SourceLocation Loc = Locs.front();
227 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
228 // If there were any diagnostics suppressed by template argument deduction,
229 // emit them now.
230 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
231 if (Pos != SuppressedDiagnostics.end()) {
232 for (const PartialDiagnosticAt &Suppressed : Pos->second)
233 Diag(Suppressed.first, Suppressed.second);
235 // Clear out the list of suppressed diagnostics, so that we don't emit
236 // them again for this specialization. However, we don't obsolete this
237 // entry from the table, because we want to avoid ever emitting these
238 // diagnostics again.
239 Pos->second.clear();
242 // C++ [basic.start.main]p3:
243 // The function 'main' shall not be used within a program.
244 if (cast<FunctionDecl>(D)->isMain())
245 Diag(Loc, diag::ext_main_used);
247 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
250 // See if this is an auto-typed variable whose initializer we are parsing.
251 if (ParsingInitForAutoVars.count(D)) {
252 if (isa<BindingDecl>(D)) {
253 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
254 << D->getDeclName();
255 } else {
256 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
257 << D->getDeclName() << cast<VarDecl>(D)->getType();
259 return true;
262 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
263 // See if this is a deleted function.
264 if (FD->isDeleted()) {
265 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
266 if (Ctor && Ctor->isInheritingConstructor())
267 Diag(Loc, diag::err_deleted_inherited_ctor_use)
268 << Ctor->getParent()
269 << Ctor->getInheritedConstructor().getConstructor()->getParent();
270 else
271 Diag(Loc, diag::err_deleted_function_use);
272 NoteDeletedFunction(FD);
273 return true;
276 // [expr.prim.id]p4
277 // A program that refers explicitly or implicitly to a function with a
278 // trailing requires-clause whose constraint-expression is not satisfied,
279 // other than to declare it, is ill-formed. [...]
281 // See if this is a function with constraints that need to be satisfied.
282 // Check this before deducing the return type, as it might instantiate the
283 // definition.
284 if (FD->getTrailingRequiresClause()) {
285 ConstraintSatisfaction Satisfaction;
286 if (CheckFunctionConstraints(FD, Satisfaction, Loc))
287 // A diagnostic will have already been generated (non-constant
288 // constraint expression, for example)
289 return true;
290 if (!Satisfaction.IsSatisfied) {
291 Diag(Loc,
292 diag::err_reference_to_function_with_unsatisfied_constraints)
293 << D;
294 DiagnoseUnsatisfiedConstraint(Satisfaction);
295 return true;
299 // If the function has a deduced return type, and we can't deduce it,
300 // then we can't use it either.
301 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
302 DeduceReturnType(FD, Loc))
303 return true;
305 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
306 return true;
308 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
309 return true;
312 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
313 // Lambdas are only default-constructible or assignable in C++2a onwards.
314 if (MD->getParent()->isLambda() &&
315 ((isa<CXXConstructorDecl>(MD) &&
316 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
317 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
318 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
319 << !isa<CXXConstructorDecl>(MD);
323 auto getReferencedObjCProp = [](const NamedDecl *D) ->
324 const ObjCPropertyDecl * {
325 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
326 return MD->findPropertyDecl();
327 return nullptr;
329 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
330 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
331 return true;
332 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
333 return true;
336 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
337 // Only the variables omp_in and omp_out are allowed in the combiner.
338 // Only the variables omp_priv and omp_orig are allowed in the
339 // initializer-clause.
340 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
341 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
342 isa<VarDecl>(D)) {
343 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
344 << getCurFunction()->HasOMPDeclareReductionCombiner;
345 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
346 return true;
349 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
350 // List-items in map clauses on this construct may only refer to the declared
351 // variable var and entities that could be referenced by a procedure defined
352 // at the same location
353 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
354 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
355 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
356 << getOpenMPDeclareMapperVarName();
357 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
358 return true;
361 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
362 Diag(Loc, diag::err_use_of_empty_using_if_exists);
363 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
364 return true;
367 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
368 AvoidPartialAvailabilityChecks, ClassReceiver);
370 DiagnoseUnusedOfDecl(*this, D, Loc);
372 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
374 if (auto *VD = dyn_cast<ValueDecl>(D))
375 checkTypeSupport(VD->getType(), Loc, VD);
377 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
378 if (!Context.getTargetInfo().isTLSSupported())
379 if (const auto *VD = dyn_cast<VarDecl>(D))
380 if (VD->getTLSKind() != VarDecl::TLS_None)
381 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
384 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
385 !isUnevaluatedContext()) {
386 // C++ [expr.prim.req.nested] p3
387 // A local parameter shall only appear as an unevaluated operand
388 // (Clause 8) within the constraint-expression.
389 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
390 << D;
391 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
392 return true;
395 return false;
398 /// DiagnoseSentinelCalls - This routine checks whether a call or
399 /// message-send is to a declaration with the sentinel attribute, and
400 /// if so, it checks that the requirements of the sentinel are
401 /// satisfied.
402 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
403 ArrayRef<Expr *> Args) {
404 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
405 if (!attr)
406 return;
408 // The number of formal parameters of the declaration.
409 unsigned numFormalParams;
411 // The kind of declaration. This is also an index into a %select in
412 // the diagnostic.
413 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
415 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
416 numFormalParams = MD->param_size();
417 calleeType = CT_Method;
418 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
419 numFormalParams = FD->param_size();
420 calleeType = CT_Function;
421 } else if (isa<VarDecl>(D)) {
422 QualType type = cast<ValueDecl>(D)->getType();
423 const FunctionType *fn = nullptr;
424 if (const PointerType *ptr = type->getAs<PointerType>()) {
425 fn = ptr->getPointeeType()->getAs<FunctionType>();
426 if (!fn) return;
427 calleeType = CT_Function;
428 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
429 fn = ptr->getPointeeType()->castAs<FunctionType>();
430 calleeType = CT_Block;
431 } else {
432 return;
435 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
436 numFormalParams = proto->getNumParams();
437 } else {
438 numFormalParams = 0;
440 } else {
441 return;
444 // "nullPos" is the number of formal parameters at the end which
445 // effectively count as part of the variadic arguments. This is
446 // useful if you would prefer to not have *any* formal parameters,
447 // but the language forces you to have at least one.
448 unsigned nullPos = attr->getNullPos();
449 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
450 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
452 // The number of arguments which should follow the sentinel.
453 unsigned numArgsAfterSentinel = attr->getSentinel();
455 // If there aren't enough arguments for all the formal parameters,
456 // the sentinel, and the args after the sentinel, complain.
457 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
458 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
459 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
460 return;
463 // Otherwise, find the sentinel expression.
464 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
465 if (!sentinelExpr) return;
466 if (sentinelExpr->isValueDependent()) return;
467 if (Context.isSentinelNullExpr(sentinelExpr)) return;
469 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
470 // or 'NULL' if those are actually defined in the context. Only use
471 // 'nil' for ObjC methods, where it's much more likely that the
472 // variadic arguments form a list of object pointers.
473 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
474 std::string NullValue;
475 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
476 NullValue = "nil";
477 else if (getLangOpts().CPlusPlus11)
478 NullValue = "nullptr";
479 else if (PP.isMacroDefined("NULL"))
480 NullValue = "NULL";
481 else
482 NullValue = "(void*) 0";
484 if (MissingNilLoc.isInvalid())
485 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
486 else
487 Diag(MissingNilLoc, diag::warn_missing_sentinel)
488 << int(calleeType)
489 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
490 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
493 SourceRange Sema::getExprRange(Expr *E) const {
494 return E ? E->getSourceRange() : SourceRange();
497 //===----------------------------------------------------------------------===//
498 // Standard Promotions and Conversions
499 //===----------------------------------------------------------------------===//
501 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
502 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
503 // Handle any placeholder expressions which made it here.
504 if (E->hasPlaceholderType()) {
505 ExprResult result = CheckPlaceholderExpr(E);
506 if (result.isInvalid()) return ExprError();
507 E = result.get();
510 QualType Ty = E->getType();
511 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
513 if (Ty->isFunctionType()) {
514 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
515 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
516 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
517 return ExprError();
519 E = ImpCastExprToType(E, Context.getPointerType(Ty),
520 CK_FunctionToPointerDecay).get();
521 } else if (Ty->isArrayType()) {
522 // In C90 mode, arrays only promote to pointers if the array expression is
523 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
524 // type 'array of type' is converted to an expression that has type 'pointer
525 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
526 // that has type 'array of type' ...". The relevant change is "an lvalue"
527 // (C90) to "an expression" (C99).
529 // C++ 4.2p1:
530 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
531 // T" can be converted to an rvalue of type "pointer to T".
533 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
534 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
535 CK_ArrayToPointerDecay);
536 if (Res.isInvalid())
537 return ExprError();
538 E = Res.get();
541 return E;
544 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
545 // Check to see if we are dereferencing a null pointer. If so,
546 // and if not volatile-qualified, this is undefined behavior that the
547 // optimizer will delete, so warn about it. People sometimes try to use this
548 // to get a deterministic trap and are surprised by clang's behavior. This
549 // only handles the pattern "*null", which is a very syntactic check.
550 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
551 if (UO && UO->getOpcode() == UO_Deref &&
552 UO->getSubExpr()->getType()->isPointerType()) {
553 const LangAS AS =
554 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
555 if ((!isTargetAddressSpace(AS) ||
556 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
557 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
558 S.Context, Expr::NPC_ValueDependentIsNotNull) &&
559 !UO->getType().isVolatileQualified()) {
560 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
561 S.PDiag(diag::warn_indirection_through_null)
562 << UO->getSubExpr()->getSourceRange());
563 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
564 S.PDiag(diag::note_indirection_through_null));
569 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
570 SourceLocation AssignLoc,
571 const Expr* RHS) {
572 const ObjCIvarDecl *IV = OIRE->getDecl();
573 if (!IV)
574 return;
576 DeclarationName MemberName = IV->getDeclName();
577 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
578 if (!Member || !Member->isStr("isa"))
579 return;
581 const Expr *Base = OIRE->getBase();
582 QualType BaseType = Base->getType();
583 if (OIRE->isArrow())
584 BaseType = BaseType->getPointeeType();
585 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
586 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
587 ObjCInterfaceDecl *ClassDeclared = nullptr;
588 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
589 if (!ClassDeclared->getSuperClass()
590 && (*ClassDeclared->ivar_begin()) == IV) {
591 if (RHS) {
592 NamedDecl *ObjectSetClass =
593 S.LookupSingleName(S.TUScope,
594 &S.Context.Idents.get("object_setClass"),
595 SourceLocation(), S.LookupOrdinaryName);
596 if (ObjectSetClass) {
597 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
598 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
599 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
600 "object_setClass(")
601 << FixItHint::CreateReplacement(
602 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
603 << FixItHint::CreateInsertion(RHSLocEnd, ")");
605 else
606 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
607 } else {
608 NamedDecl *ObjectGetClass =
609 S.LookupSingleName(S.TUScope,
610 &S.Context.Idents.get("object_getClass"),
611 SourceLocation(), S.LookupOrdinaryName);
612 if (ObjectGetClass)
613 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
614 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
615 "object_getClass(")
616 << FixItHint::CreateReplacement(
617 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
618 else
619 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
621 S.Diag(IV->getLocation(), diag::note_ivar_decl);
626 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
627 // Handle any placeholder expressions which made it here.
628 if (E->hasPlaceholderType()) {
629 ExprResult result = CheckPlaceholderExpr(E);
630 if (result.isInvalid()) return ExprError();
631 E = result.get();
634 // C++ [conv.lval]p1:
635 // A glvalue of a non-function, non-array type T can be
636 // converted to a prvalue.
637 if (!E->isGLValue()) return E;
639 QualType T = E->getType();
640 assert(!T.isNull() && "r-value conversion on typeless expression?");
642 // lvalue-to-rvalue conversion cannot be applied to function or array types.
643 if (T->isFunctionType() || T->isArrayType())
644 return E;
646 // We don't want to throw lvalue-to-rvalue casts on top of
647 // expressions of certain types in C++.
648 if (getLangOpts().CPlusPlus &&
649 (E->getType() == Context.OverloadTy ||
650 T->isDependentType() ||
651 T->isRecordType()))
652 return E;
654 // The C standard is actually really unclear on this point, and
655 // DR106 tells us what the result should be but not why. It's
656 // generally best to say that void types just doesn't undergo
657 // lvalue-to-rvalue at all. Note that expressions of unqualified
658 // 'void' type are never l-values, but qualified void can be.
659 if (T->isVoidType())
660 return E;
662 // OpenCL usually rejects direct accesses to values of 'half' type.
663 if (getLangOpts().OpenCL &&
664 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
665 T->isHalfType()) {
666 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
667 << 0 << T;
668 return ExprError();
671 CheckForNullPointerDereference(*this, E);
672 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
673 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
674 &Context.Idents.get("object_getClass"),
675 SourceLocation(), LookupOrdinaryName);
676 if (ObjectGetClass)
677 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
678 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
679 << FixItHint::CreateReplacement(
680 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
681 else
682 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
684 else if (const ObjCIvarRefExpr *OIRE =
685 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
686 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
688 // C++ [conv.lval]p1:
689 // [...] If T is a non-class type, the type of the prvalue is the
690 // cv-unqualified version of T. Otherwise, the type of the
691 // rvalue is T.
693 // C99 6.3.2.1p2:
694 // If the lvalue has qualified type, the value has the unqualified
695 // version of the type of the lvalue; otherwise, the value has the
696 // type of the lvalue.
697 if (T.hasQualifiers())
698 T = T.getUnqualifiedType();
700 // Under the MS ABI, lock down the inheritance model now.
701 if (T->isMemberPointerType() &&
702 Context.getTargetInfo().getCXXABI().isMicrosoft())
703 (void)isCompleteType(E->getExprLoc(), T);
705 ExprResult Res = CheckLValueToRValueConversionOperand(E);
706 if (Res.isInvalid())
707 return Res;
708 E = Res.get();
710 // Loading a __weak object implicitly retains the value, so we need a cleanup to
711 // balance that.
712 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
713 Cleanup.setExprNeedsCleanups(true);
715 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
716 Cleanup.setExprNeedsCleanups(true);
718 // C++ [conv.lval]p3:
719 // If T is cv std::nullptr_t, the result is a null pointer constant.
720 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
721 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
722 CurFPFeatureOverrides());
724 // C11 6.3.2.1p2:
725 // ... if the lvalue has atomic type, the value has the non-atomic version
726 // of the type of the lvalue ...
727 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
728 T = Atomic->getValueType().getUnqualifiedType();
729 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
730 nullptr, VK_PRValue, FPOptionsOverride());
733 return Res;
736 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
737 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
738 if (Res.isInvalid())
739 return ExprError();
740 Res = DefaultLvalueConversion(Res.get());
741 if (Res.isInvalid())
742 return ExprError();
743 return Res;
746 /// CallExprUnaryConversions - a special case of an unary conversion
747 /// performed on a function designator of a call expression.
748 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
749 QualType Ty = E->getType();
750 ExprResult Res = E;
751 // Only do implicit cast for a function type, but not for a pointer
752 // to function type.
753 if (Ty->isFunctionType()) {
754 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
755 CK_FunctionToPointerDecay);
756 if (Res.isInvalid())
757 return ExprError();
759 Res = DefaultLvalueConversion(Res.get());
760 if (Res.isInvalid())
761 return ExprError();
762 return Res.get();
765 /// UsualUnaryConversions - Performs various conversions that are common to most
766 /// operators (C99 6.3). The conversions of array and function types are
767 /// sometimes suppressed. For example, the array->pointer conversion doesn't
768 /// apply if the array is an argument to the sizeof or address (&) operators.
769 /// In these instances, this routine should *not* be called.
770 ExprResult Sema::UsualUnaryConversions(Expr *E) {
771 // First, convert to an r-value.
772 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
773 if (Res.isInvalid())
774 return ExprError();
775 E = Res.get();
777 QualType Ty = E->getType();
778 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
780 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
781 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
782 (getLangOpts().getFPEvalMethod() !=
783 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
784 PP.getLastFPEvalPragmaLocation().isValid())) {
785 switch (EvalMethod) {
786 default:
787 llvm_unreachable("Unrecognized float evaluation method");
788 break;
789 case LangOptions::FEM_UnsetOnCommandLine:
790 llvm_unreachable("Float evaluation method should be set by now");
791 break;
792 case LangOptions::FEM_Double:
793 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
794 // Widen the expression to double.
795 return Ty->isComplexType()
796 ? ImpCastExprToType(E,
797 Context.getComplexType(Context.DoubleTy),
798 CK_FloatingComplexCast)
799 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
800 break;
801 case LangOptions::FEM_Extended:
802 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
803 // Widen the expression to long double.
804 return Ty->isComplexType()
805 ? ImpCastExprToType(
806 E, Context.getComplexType(Context.LongDoubleTy),
807 CK_FloatingComplexCast)
808 : ImpCastExprToType(E, Context.LongDoubleTy,
809 CK_FloatingCast);
810 break;
814 // Half FP have to be promoted to float unless it is natively supported
815 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
816 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
818 // Try to perform integral promotions if the object has a theoretically
819 // promotable type.
820 if (Ty->isIntegralOrUnscopedEnumerationType()) {
821 // C99 6.3.1.1p2:
823 // The following may be used in an expression wherever an int or
824 // unsigned int may be used:
825 // - an object or expression with an integer type whose integer
826 // conversion rank is less than or equal to the rank of int
827 // and unsigned int.
828 // - A bit-field of type _Bool, int, signed int, or unsigned int.
830 // If an int can represent all values of the original type, the
831 // value is converted to an int; otherwise, it is converted to an
832 // unsigned int. These are called the integer promotions. All
833 // other types are unchanged by the integer promotions.
835 QualType PTy = Context.isPromotableBitField(E);
836 if (!PTy.isNull()) {
837 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
838 return E;
840 if (Ty->isPromotableIntegerType()) {
841 QualType PT = Context.getPromotedIntegerType(Ty);
842 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
843 return E;
846 return E;
849 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
850 /// do not have a prototype. Arguments that have type float or __fp16
851 /// are promoted to double. All other argument types are converted by
852 /// UsualUnaryConversions().
853 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
854 QualType Ty = E->getType();
855 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
857 ExprResult Res = UsualUnaryConversions(E);
858 if (Res.isInvalid())
859 return ExprError();
860 E = Res.get();
862 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
863 // promote to double.
864 // Note that default argument promotion applies only to float (and
865 // half/fp16); it does not apply to _Float16.
866 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
867 if (BTy && (BTy->getKind() == BuiltinType::Half ||
868 BTy->getKind() == BuiltinType::Float)) {
869 if (getLangOpts().OpenCL &&
870 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
871 if (BTy->getKind() == BuiltinType::Half) {
872 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
874 } else {
875 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
878 if (BTy &&
879 getLangOpts().getExtendIntArgs() ==
880 LangOptions::ExtendArgsKind::ExtendTo64 &&
881 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
882 Context.getTypeSizeInChars(BTy) <
883 Context.getTypeSizeInChars(Context.LongLongTy)) {
884 E = (Ty->isUnsignedIntegerType())
885 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
886 .get()
887 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
888 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
889 "Unexpected typesize for LongLongTy");
892 // C++ performs lvalue-to-rvalue conversion as a default argument
893 // promotion, even on class types, but note:
894 // C++11 [conv.lval]p2:
895 // When an lvalue-to-rvalue conversion occurs in an unevaluated
896 // operand or a subexpression thereof the value contained in the
897 // referenced object is not accessed. Otherwise, if the glvalue
898 // has a class type, the conversion copy-initializes a temporary
899 // of type T from the glvalue and the result of the conversion
900 // is a prvalue for the temporary.
901 // FIXME: add some way to gate this entire thing for correctness in
902 // potentially potentially evaluated contexts.
903 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
904 ExprResult Temp = PerformCopyInitialization(
905 InitializedEntity::InitializeTemporary(E->getType()),
906 E->getExprLoc(), E);
907 if (Temp.isInvalid())
908 return ExprError();
909 E = Temp.get();
912 return E;
915 /// Determine the degree of POD-ness for an expression.
916 /// Incomplete types are considered POD, since this check can be performed
917 /// when we're in an unevaluated context.
918 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
919 if (Ty->isIncompleteType()) {
920 // C++11 [expr.call]p7:
921 // After these conversions, if the argument does not have arithmetic,
922 // enumeration, pointer, pointer to member, or class type, the program
923 // is ill-formed.
925 // Since we've already performed array-to-pointer and function-to-pointer
926 // decay, the only such type in C++ is cv void. This also handles
927 // initializer lists as variadic arguments.
928 if (Ty->isVoidType())
929 return VAK_Invalid;
931 if (Ty->isObjCObjectType())
932 return VAK_Invalid;
933 return VAK_Valid;
936 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
937 return VAK_Invalid;
939 if (Ty.isCXX98PODType(Context))
940 return VAK_Valid;
942 // C++11 [expr.call]p7:
943 // Passing a potentially-evaluated argument of class type (Clause 9)
944 // having a non-trivial copy constructor, a non-trivial move constructor,
945 // or a non-trivial destructor, with no corresponding parameter,
946 // is conditionally-supported with implementation-defined semantics.
947 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
948 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
949 if (!Record->hasNonTrivialCopyConstructor() &&
950 !Record->hasNonTrivialMoveConstructor() &&
951 !Record->hasNonTrivialDestructor())
952 return VAK_ValidInCXX11;
954 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
955 return VAK_Valid;
957 if (Ty->isObjCObjectType())
958 return VAK_Invalid;
960 if (getLangOpts().MSVCCompat)
961 return VAK_MSVCUndefined;
963 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
964 // permitted to reject them. We should consider doing so.
965 return VAK_Undefined;
968 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
969 // Don't allow one to pass an Objective-C interface to a vararg.
970 const QualType &Ty = E->getType();
971 VarArgKind VAK = isValidVarArgType(Ty);
973 // Complain about passing non-POD types through varargs.
974 switch (VAK) {
975 case VAK_ValidInCXX11:
976 DiagRuntimeBehavior(
977 E->getBeginLoc(), nullptr,
978 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
979 [[fallthrough]];
980 case VAK_Valid:
981 if (Ty->isRecordType()) {
982 // This is unlikely to be what the user intended. If the class has a
983 // 'c_str' member function, the user probably meant to call that.
984 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
985 PDiag(diag::warn_pass_class_arg_to_vararg)
986 << Ty << CT << hasCStrMethod(E) << ".c_str()");
988 break;
990 case VAK_Undefined:
991 case VAK_MSVCUndefined:
992 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
993 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
994 << getLangOpts().CPlusPlus11 << Ty << CT);
995 break;
997 case VAK_Invalid:
998 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
999 Diag(E->getBeginLoc(),
1000 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1001 << Ty << CT;
1002 else if (Ty->isObjCObjectType())
1003 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1004 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1005 << Ty << CT);
1006 else
1007 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1008 << isa<InitListExpr>(E) << Ty << CT;
1009 break;
1013 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1014 /// will create a trap if the resulting type is not a POD type.
1015 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1016 FunctionDecl *FDecl) {
1017 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1018 // Strip the unbridged-cast placeholder expression off, if applicable.
1019 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1020 (CT == VariadicMethod ||
1021 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1022 E = stripARCUnbridgedCast(E);
1024 // Otherwise, do normal placeholder checking.
1025 } else {
1026 ExprResult ExprRes = CheckPlaceholderExpr(E);
1027 if (ExprRes.isInvalid())
1028 return ExprError();
1029 E = ExprRes.get();
1033 ExprResult ExprRes = DefaultArgumentPromotion(E);
1034 if (ExprRes.isInvalid())
1035 return ExprError();
1037 // Copy blocks to the heap.
1038 if (ExprRes.get()->getType()->isBlockPointerType())
1039 maybeExtendBlockObject(ExprRes);
1041 E = ExprRes.get();
1043 // Diagnostics regarding non-POD argument types are
1044 // emitted along with format string checking in Sema::CheckFunctionCall().
1045 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1046 // Turn this into a trap.
1047 CXXScopeSpec SS;
1048 SourceLocation TemplateKWLoc;
1049 UnqualifiedId Name;
1050 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1051 E->getBeginLoc());
1052 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1053 /*HasTrailingLParen=*/true,
1054 /*IsAddressOfOperand=*/false);
1055 if (TrapFn.isInvalid())
1056 return ExprError();
1058 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1059 None, E->getEndLoc());
1060 if (Call.isInvalid())
1061 return ExprError();
1063 ExprResult Comma =
1064 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1065 if (Comma.isInvalid())
1066 return ExprError();
1067 return Comma.get();
1070 if (!getLangOpts().CPlusPlus &&
1071 RequireCompleteType(E->getExprLoc(), E->getType(),
1072 diag::err_call_incomplete_argument))
1073 return ExprError();
1075 return E;
1078 /// Converts an integer to complex float type. Helper function of
1079 /// UsualArithmeticConversions()
1081 /// \return false if the integer expression is an integer type and is
1082 /// successfully converted to the complex type.
1083 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1084 ExprResult &ComplexExpr,
1085 QualType IntTy,
1086 QualType ComplexTy,
1087 bool SkipCast) {
1088 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1089 if (SkipCast) return false;
1090 if (IntTy->isIntegerType()) {
1091 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1092 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1093 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1094 CK_FloatingRealToComplex);
1095 } else {
1096 assert(IntTy->isComplexIntegerType());
1097 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1098 CK_IntegralComplexToFloatingComplex);
1100 return false;
1103 // This handles complex/complex, complex/float, or float/complex.
1104 // When both operands are complex, the shorter operand is converted to the
1105 // type of the longer, and that is the type of the result. This corresponds
1106 // to what is done when combining two real floating-point operands.
1107 // The fun begins when size promotion occur across type domains.
1108 // From H&S 6.3.4: When one operand is complex and the other is a real
1109 // floating-point type, the less precise type is converted, within it's
1110 // real or complex domain, to the precision of the other type. For example,
1111 // when combining a "long double" with a "double _Complex", the
1112 // "double _Complex" is promoted to "long double _Complex".
1113 static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter,
1114 QualType ShorterType,
1115 QualType LongerType,
1116 bool PromotePrecision) {
1117 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1118 QualType Result =
1119 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1121 if (PromotePrecision) {
1122 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1123 Shorter =
1124 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1125 } else {
1126 if (LongerIsComplex)
1127 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1128 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1131 return Result;
1134 /// Handle arithmetic conversion with complex types. Helper function of
1135 /// UsualArithmeticConversions()
1136 static QualType handleComplexConversion(Sema &S, ExprResult &LHS,
1137 ExprResult &RHS, QualType LHSType,
1138 QualType RHSType, bool IsCompAssign) {
1139 // if we have an integer operand, the result is the complex type.
1140 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1141 /*SkipCast=*/false))
1142 return LHSType;
1143 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1144 /*SkipCast=*/IsCompAssign))
1145 return RHSType;
1147 // Compute the rank of the two types, regardless of whether they are complex.
1148 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1149 if (Order < 0)
1150 // Promote the precision of the LHS if not an assignment.
1151 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1152 /*PromotePrecision=*/!IsCompAssign);
1153 // Promote the precision of the RHS unless it is already the same as the LHS.
1154 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1155 /*PromotePrecision=*/Order > 0);
1158 /// Handle arithmetic conversion from integer to float. Helper function
1159 /// of UsualArithmeticConversions()
1160 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1161 ExprResult &IntExpr,
1162 QualType FloatTy, QualType IntTy,
1163 bool ConvertFloat, bool ConvertInt) {
1164 if (IntTy->isIntegerType()) {
1165 if (ConvertInt)
1166 // Convert intExpr to the lhs floating point type.
1167 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1168 CK_IntegralToFloating);
1169 return FloatTy;
1172 // Convert both sides to the appropriate complex float.
1173 assert(IntTy->isComplexIntegerType());
1174 QualType result = S.Context.getComplexType(FloatTy);
1176 // _Complex int -> _Complex float
1177 if (ConvertInt)
1178 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1179 CK_IntegralComplexToFloatingComplex);
1181 // float -> _Complex float
1182 if (ConvertFloat)
1183 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1184 CK_FloatingRealToComplex);
1186 return result;
1189 /// Handle arithmethic conversion with floating point types. Helper
1190 /// function of UsualArithmeticConversions()
1191 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1192 ExprResult &RHS, QualType LHSType,
1193 QualType RHSType, bool IsCompAssign) {
1194 bool LHSFloat = LHSType->isRealFloatingType();
1195 bool RHSFloat = RHSType->isRealFloatingType();
1197 // N1169 4.1.4: If one of the operands has a floating type and the other
1198 // operand has a fixed-point type, the fixed-point operand
1199 // is converted to the floating type [...]
1200 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1201 if (LHSFloat)
1202 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1203 else if (!IsCompAssign)
1204 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1205 return LHSFloat ? LHSType : RHSType;
1208 // If we have two real floating types, convert the smaller operand
1209 // to the bigger result.
1210 if (LHSFloat && RHSFloat) {
1211 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1212 if (order > 0) {
1213 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1214 return LHSType;
1217 assert(order < 0 && "illegal float comparison");
1218 if (!IsCompAssign)
1219 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1220 return RHSType;
1223 if (LHSFloat) {
1224 // Half FP has to be promoted to float unless it is natively supported
1225 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1226 LHSType = S.Context.FloatTy;
1228 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1229 /*ConvertFloat=*/!IsCompAssign,
1230 /*ConvertInt=*/ true);
1232 assert(RHSFloat);
1233 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1234 /*ConvertFloat=*/ true,
1235 /*ConvertInt=*/!IsCompAssign);
1238 /// Diagnose attempts to convert between __float128, __ibm128 and
1239 /// long double if there is no support for such conversion.
1240 /// Helper function of UsualArithmeticConversions().
1241 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1242 QualType RHSType) {
1243 // No issue if either is not a floating point type.
1244 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1245 return false;
1247 // No issue if both have the same 128-bit float semantics.
1248 auto *LHSComplex = LHSType->getAs<ComplexType>();
1249 auto *RHSComplex = RHSType->getAs<ComplexType>();
1251 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1252 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1254 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1255 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1257 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1258 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1259 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1260 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1261 return false;
1263 return true;
1266 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1268 namespace {
1269 /// These helper callbacks are placed in an anonymous namespace to
1270 /// permit their use as function template parameters.
1271 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1272 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1275 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1276 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1277 CK_IntegralComplexCast);
1281 /// Handle integer arithmetic conversions. Helper function of
1282 /// UsualArithmeticConversions()
1283 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1284 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1285 ExprResult &RHS, QualType LHSType,
1286 QualType RHSType, bool IsCompAssign) {
1287 // The rules for this case are in C99 6.3.1.8
1288 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1289 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1290 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1291 if (LHSSigned == RHSSigned) {
1292 // Same signedness; use the higher-ranked type
1293 if (order >= 0) {
1294 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1295 return LHSType;
1296 } else if (!IsCompAssign)
1297 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1298 return RHSType;
1299 } else if (order != (LHSSigned ? 1 : -1)) {
1300 // The unsigned type has greater than or equal rank to the
1301 // signed type, so use the unsigned type
1302 if (RHSSigned) {
1303 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1304 return LHSType;
1305 } else if (!IsCompAssign)
1306 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1307 return RHSType;
1308 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1309 // The two types are different widths; if we are here, that
1310 // means the signed type is larger than the unsigned type, so
1311 // use the signed type.
1312 if (LHSSigned) {
1313 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1314 return LHSType;
1315 } else if (!IsCompAssign)
1316 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1317 return RHSType;
1318 } else {
1319 // The signed type is higher-ranked than the unsigned type,
1320 // but isn't actually any bigger (like unsigned int and long
1321 // on most 32-bit systems). Use the unsigned type corresponding
1322 // to the signed type.
1323 QualType result =
1324 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1325 RHS = (*doRHSCast)(S, RHS.get(), result);
1326 if (!IsCompAssign)
1327 LHS = (*doLHSCast)(S, LHS.get(), result);
1328 return result;
1332 /// Handle conversions with GCC complex int extension. Helper function
1333 /// of UsualArithmeticConversions()
1334 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1335 ExprResult &RHS, QualType LHSType,
1336 QualType RHSType,
1337 bool IsCompAssign) {
1338 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1339 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1341 if (LHSComplexInt && RHSComplexInt) {
1342 QualType LHSEltType = LHSComplexInt->getElementType();
1343 QualType RHSEltType = RHSComplexInt->getElementType();
1344 QualType ScalarType =
1345 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1346 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1348 return S.Context.getComplexType(ScalarType);
1351 if (LHSComplexInt) {
1352 QualType LHSEltType = LHSComplexInt->getElementType();
1353 QualType ScalarType =
1354 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1355 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1356 QualType ComplexType = S.Context.getComplexType(ScalarType);
1357 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1358 CK_IntegralRealToComplex);
1360 return ComplexType;
1363 assert(RHSComplexInt);
1365 QualType RHSEltType = RHSComplexInt->getElementType();
1366 QualType ScalarType =
1367 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1368 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1369 QualType ComplexType = S.Context.getComplexType(ScalarType);
1371 if (!IsCompAssign)
1372 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1373 CK_IntegralRealToComplex);
1374 return ComplexType;
1377 /// Return the rank of a given fixed point or integer type. The value itself
1378 /// doesn't matter, but the values must be increasing with proper increasing
1379 /// rank as described in N1169 4.1.1.
1380 static unsigned GetFixedPointRank(QualType Ty) {
1381 const auto *BTy = Ty->getAs<BuiltinType>();
1382 assert(BTy && "Expected a builtin type.");
1384 switch (BTy->getKind()) {
1385 case BuiltinType::ShortFract:
1386 case BuiltinType::UShortFract:
1387 case BuiltinType::SatShortFract:
1388 case BuiltinType::SatUShortFract:
1389 return 1;
1390 case BuiltinType::Fract:
1391 case BuiltinType::UFract:
1392 case BuiltinType::SatFract:
1393 case BuiltinType::SatUFract:
1394 return 2;
1395 case BuiltinType::LongFract:
1396 case BuiltinType::ULongFract:
1397 case BuiltinType::SatLongFract:
1398 case BuiltinType::SatULongFract:
1399 return 3;
1400 case BuiltinType::ShortAccum:
1401 case BuiltinType::UShortAccum:
1402 case BuiltinType::SatShortAccum:
1403 case BuiltinType::SatUShortAccum:
1404 return 4;
1405 case BuiltinType::Accum:
1406 case BuiltinType::UAccum:
1407 case BuiltinType::SatAccum:
1408 case BuiltinType::SatUAccum:
1409 return 5;
1410 case BuiltinType::LongAccum:
1411 case BuiltinType::ULongAccum:
1412 case BuiltinType::SatLongAccum:
1413 case BuiltinType::SatULongAccum:
1414 return 6;
1415 default:
1416 if (BTy->isInteger())
1417 return 0;
1418 llvm_unreachable("Unexpected fixed point or integer type");
1422 /// handleFixedPointConversion - Fixed point operations between fixed
1423 /// point types and integers or other fixed point types do not fall under
1424 /// usual arithmetic conversion since these conversions could result in loss
1425 /// of precsision (N1169 4.1.4). These operations should be calculated with
1426 /// the full precision of their result type (N1169 4.1.6.2.1).
1427 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1428 QualType RHSTy) {
1429 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1430 "Expected at least one of the operands to be a fixed point type");
1431 assert((LHSTy->isFixedPointOrIntegerType() ||
1432 RHSTy->isFixedPointOrIntegerType()) &&
1433 "Special fixed point arithmetic operation conversions are only "
1434 "applied to ints or other fixed point types");
1436 // If one operand has signed fixed-point type and the other operand has
1437 // unsigned fixed-point type, then the unsigned fixed-point operand is
1438 // converted to its corresponding signed fixed-point type and the resulting
1439 // type is the type of the converted operand.
1440 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1441 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1442 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1443 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1445 // The result type is the type with the highest rank, whereby a fixed-point
1446 // conversion rank is always greater than an integer conversion rank; if the
1447 // type of either of the operands is a saturating fixedpoint type, the result
1448 // type shall be the saturating fixed-point type corresponding to the type
1449 // with the highest rank; the resulting value is converted (taking into
1450 // account rounding and overflow) to the precision of the resulting type.
1451 // Same ranks between signed and unsigned types are resolved earlier, so both
1452 // types are either signed or both unsigned at this point.
1453 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1454 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1456 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1458 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1459 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1461 return ResultTy;
1464 /// Check that the usual arithmetic conversions can be performed on this pair of
1465 /// expressions that might be of enumeration type.
1466 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1467 SourceLocation Loc,
1468 Sema::ArithConvKind ACK) {
1469 // C++2a [expr.arith.conv]p1:
1470 // If one operand is of enumeration type and the other operand is of a
1471 // different enumeration type or a floating-point type, this behavior is
1472 // deprecated ([depr.arith.conv.enum]).
1474 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1475 // Eventually we will presumably reject these cases (in C++23 onwards?).
1476 QualType L = LHS->getType(), R = RHS->getType();
1477 bool LEnum = L->isUnscopedEnumerationType(),
1478 REnum = R->isUnscopedEnumerationType();
1479 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1480 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1481 (REnum && L->isFloatingType())) {
1482 S.Diag(Loc, S.getLangOpts().CPlusPlus20
1483 ? diag::warn_arith_conv_enum_float_cxx20
1484 : diag::warn_arith_conv_enum_float)
1485 << LHS->getSourceRange() << RHS->getSourceRange()
1486 << (int)ACK << LEnum << L << R;
1487 } else if (!IsCompAssign && LEnum && REnum &&
1488 !S.Context.hasSameUnqualifiedType(L, R)) {
1489 unsigned DiagID;
1490 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1491 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1492 // If either enumeration type is unnamed, it's less likely that the
1493 // user cares about this, but this situation is still deprecated in
1494 // C++2a. Use a different warning group.
1495 DiagID = S.getLangOpts().CPlusPlus20
1496 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1497 : diag::warn_arith_conv_mixed_anon_enum_types;
1498 } else if (ACK == Sema::ACK_Conditional) {
1499 // Conditional expressions are separated out because they have
1500 // historically had a different warning flag.
1501 DiagID = S.getLangOpts().CPlusPlus20
1502 ? diag::warn_conditional_mixed_enum_types_cxx20
1503 : diag::warn_conditional_mixed_enum_types;
1504 } else if (ACK == Sema::ACK_Comparison) {
1505 // Comparison expressions are separated out because they have
1506 // historically had a different warning flag.
1507 DiagID = S.getLangOpts().CPlusPlus20
1508 ? diag::warn_comparison_mixed_enum_types_cxx20
1509 : diag::warn_comparison_mixed_enum_types;
1510 } else {
1511 DiagID = S.getLangOpts().CPlusPlus20
1512 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1513 : diag::warn_arith_conv_mixed_enum_types;
1515 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1516 << (int)ACK << L << R;
1520 /// UsualArithmeticConversions - Performs various conversions that are common to
1521 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1522 /// routine returns the first non-arithmetic type found. The client is
1523 /// responsible for emitting appropriate error diagnostics.
1524 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1525 SourceLocation Loc,
1526 ArithConvKind ACK) {
1527 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1529 if (ACK != ACK_CompAssign) {
1530 LHS = UsualUnaryConversions(LHS.get());
1531 if (LHS.isInvalid())
1532 return QualType();
1535 RHS = UsualUnaryConversions(RHS.get());
1536 if (RHS.isInvalid())
1537 return QualType();
1539 // For conversion purposes, we ignore any qualifiers.
1540 // For example, "const float" and "float" are equivalent.
1541 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1542 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1544 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1545 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1546 LHSType = AtomicLHS->getValueType();
1548 // If both types are identical, no conversion is needed.
1549 if (Context.hasSameType(LHSType, RHSType))
1550 return Context.getCommonSugaredType(LHSType, RHSType);
1552 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1553 // The caller can deal with this (e.g. pointer + int).
1554 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1555 return QualType();
1557 // Apply unary and bitfield promotions to the LHS's type.
1558 QualType LHSUnpromotedType = LHSType;
1559 if (LHSType->isPromotableIntegerType())
1560 LHSType = Context.getPromotedIntegerType(LHSType);
1561 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1562 if (!LHSBitfieldPromoteTy.isNull())
1563 LHSType = LHSBitfieldPromoteTy;
1564 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1565 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1567 // If both types are identical, no conversion is needed.
1568 if (Context.hasSameType(LHSType, RHSType))
1569 return Context.getCommonSugaredType(LHSType, RHSType);
1571 // At this point, we have two different arithmetic types.
1573 // Diagnose attempts to convert between __ibm128, __float128 and long double
1574 // where such conversions currently can't be handled.
1575 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1576 return QualType();
1578 // Handle complex types first (C99 6.3.1.8p1).
1579 if (LHSType->isComplexType() || RHSType->isComplexType())
1580 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1581 ACK == ACK_CompAssign);
1583 // Now handle "real" floating types (i.e. float, double, long double).
1584 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1585 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1586 ACK == ACK_CompAssign);
1588 // Handle GCC complex int extension.
1589 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1590 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1591 ACK == ACK_CompAssign);
1593 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1594 return handleFixedPointConversion(*this, LHSType, RHSType);
1596 // Finally, we have two differing integer types.
1597 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1598 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1601 //===----------------------------------------------------------------------===//
1602 // Semantic Analysis for various Expression Types
1603 //===----------------------------------------------------------------------===//
1606 ExprResult
1607 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1608 SourceLocation DefaultLoc,
1609 SourceLocation RParenLoc,
1610 Expr *ControllingExpr,
1611 ArrayRef<ParsedType> ArgTypes,
1612 ArrayRef<Expr *> ArgExprs) {
1613 unsigned NumAssocs = ArgTypes.size();
1614 assert(NumAssocs == ArgExprs.size());
1616 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1617 for (unsigned i = 0; i < NumAssocs; ++i) {
1618 if (ArgTypes[i])
1619 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1620 else
1621 Types[i] = nullptr;
1624 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1625 ControllingExpr,
1626 llvm::makeArrayRef(Types, NumAssocs),
1627 ArgExprs);
1628 delete [] Types;
1629 return ER;
1632 ExprResult
1633 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1634 SourceLocation DefaultLoc,
1635 SourceLocation RParenLoc,
1636 Expr *ControllingExpr,
1637 ArrayRef<TypeSourceInfo *> Types,
1638 ArrayRef<Expr *> Exprs) {
1639 unsigned NumAssocs = Types.size();
1640 assert(NumAssocs == Exprs.size());
1642 // Decay and strip qualifiers for the controlling expression type, and handle
1643 // placeholder type replacement. See committee discussion from WG14 DR423.
1645 EnterExpressionEvaluationContext Unevaluated(
1646 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1647 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1648 if (R.isInvalid())
1649 return ExprError();
1650 ControllingExpr = R.get();
1653 bool TypeErrorFound = false,
1654 IsResultDependent = ControllingExpr->isTypeDependent(),
1655 ContainsUnexpandedParameterPack
1656 = ControllingExpr->containsUnexpandedParameterPack();
1658 // The controlling expression is an unevaluated operand, so side effects are
1659 // likely unintended.
1660 if (!inTemplateInstantiation() && !IsResultDependent &&
1661 ControllingExpr->HasSideEffects(Context, false))
1662 Diag(ControllingExpr->getExprLoc(),
1663 diag::warn_side_effects_unevaluated_context);
1665 for (unsigned i = 0; i < NumAssocs; ++i) {
1666 if (Exprs[i]->containsUnexpandedParameterPack())
1667 ContainsUnexpandedParameterPack = true;
1669 if (Types[i]) {
1670 if (Types[i]->getType()->containsUnexpandedParameterPack())
1671 ContainsUnexpandedParameterPack = true;
1673 if (Types[i]->getType()->isDependentType()) {
1674 IsResultDependent = true;
1675 } else {
1676 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1677 // complete object type other than a variably modified type."
1678 unsigned D = 0;
1679 if (Types[i]->getType()->isIncompleteType())
1680 D = diag::err_assoc_type_incomplete;
1681 else if (!Types[i]->getType()->isObjectType())
1682 D = diag::err_assoc_type_nonobject;
1683 else if (Types[i]->getType()->isVariablyModifiedType())
1684 D = diag::err_assoc_type_variably_modified;
1685 else {
1686 // Because the controlling expression undergoes lvalue conversion,
1687 // array conversion, and function conversion, an association which is
1688 // of array type, function type, or is qualified can never be
1689 // reached. We will warn about this so users are less surprised by
1690 // the unreachable association. However, we don't have to handle
1691 // function types; that's not an object type, so it's handled above.
1693 // The logic is somewhat different for C++ because C++ has different
1694 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1695 // If T is a non-class type, the type of the prvalue is the cv-
1696 // unqualified version of T. Otherwise, the type of the prvalue is T.
1697 // The result of these rules is that all qualified types in an
1698 // association in C are unreachable, and in C++, only qualified non-
1699 // class types are unreachable.
1700 unsigned Reason = 0;
1701 QualType QT = Types[i]->getType();
1702 if (QT->isArrayType())
1703 Reason = 1;
1704 else if (QT.hasQualifiers() &&
1705 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1706 Reason = 2;
1708 if (Reason)
1709 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1710 diag::warn_unreachable_association)
1711 << QT << (Reason - 1);
1714 if (D != 0) {
1715 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1716 << Types[i]->getTypeLoc().getSourceRange()
1717 << Types[i]->getType();
1718 TypeErrorFound = true;
1721 // C11 6.5.1.1p2 "No two generic associations in the same generic
1722 // selection shall specify compatible types."
1723 for (unsigned j = i+1; j < NumAssocs; ++j)
1724 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1725 Context.typesAreCompatible(Types[i]->getType(),
1726 Types[j]->getType())) {
1727 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1728 diag::err_assoc_compatible_types)
1729 << Types[j]->getTypeLoc().getSourceRange()
1730 << Types[j]->getType()
1731 << Types[i]->getType();
1732 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1733 diag::note_compat_assoc)
1734 << Types[i]->getTypeLoc().getSourceRange()
1735 << Types[i]->getType();
1736 TypeErrorFound = true;
1741 if (TypeErrorFound)
1742 return ExprError();
1744 // If we determined that the generic selection is result-dependent, don't
1745 // try to compute the result expression.
1746 if (IsResultDependent)
1747 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1748 Exprs, DefaultLoc, RParenLoc,
1749 ContainsUnexpandedParameterPack);
1751 SmallVector<unsigned, 1> CompatIndices;
1752 unsigned DefaultIndex = -1U;
1753 // Look at the canonical type of the controlling expression in case it was a
1754 // deduced type like __auto_type. However, when issuing diagnostics, use the
1755 // type the user wrote in source rather than the canonical one.
1756 for (unsigned i = 0; i < NumAssocs; ++i) {
1757 if (!Types[i])
1758 DefaultIndex = i;
1759 else if (Context.typesAreCompatible(
1760 ControllingExpr->getType().getCanonicalType(),
1761 Types[i]->getType()))
1762 CompatIndices.push_back(i);
1765 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1766 // type compatible with at most one of the types named in its generic
1767 // association list."
1768 if (CompatIndices.size() > 1) {
1769 // We strip parens here because the controlling expression is typically
1770 // parenthesized in macro definitions.
1771 ControllingExpr = ControllingExpr->IgnoreParens();
1772 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1773 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1774 << (unsigned)CompatIndices.size();
1775 for (unsigned I : CompatIndices) {
1776 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1777 diag::note_compat_assoc)
1778 << Types[I]->getTypeLoc().getSourceRange()
1779 << Types[I]->getType();
1781 return ExprError();
1784 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1785 // its controlling expression shall have type compatible with exactly one of
1786 // the types named in its generic association list."
1787 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1788 // We strip parens here because the controlling expression is typically
1789 // parenthesized in macro definitions.
1790 ControllingExpr = ControllingExpr->IgnoreParens();
1791 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1792 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1793 return ExprError();
1796 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1797 // type name that is compatible with the type of the controlling expression,
1798 // then the result expression of the generic selection is the expression
1799 // in that generic association. Otherwise, the result expression of the
1800 // generic selection is the expression in the default generic association."
1801 unsigned ResultIndex =
1802 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1804 return GenericSelectionExpr::Create(
1805 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1806 ContainsUnexpandedParameterPack, ResultIndex);
1809 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1810 /// location of the token and the offset of the ud-suffix within it.
1811 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1812 unsigned Offset) {
1813 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1814 S.getLangOpts());
1817 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1818 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1819 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1820 IdentifierInfo *UDSuffix,
1821 SourceLocation UDSuffixLoc,
1822 ArrayRef<Expr*> Args,
1823 SourceLocation LitEndLoc) {
1824 assert(Args.size() <= 2 && "too many arguments for literal operator");
1826 QualType ArgTy[2];
1827 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1828 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1829 if (ArgTy[ArgIdx]->isArrayType())
1830 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1833 DeclarationName OpName =
1834 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1835 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1836 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1838 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1839 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1840 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1841 /*AllowStringTemplatePack*/ false,
1842 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1843 return ExprError();
1845 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1848 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1849 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1850 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1851 /// multiple tokens. However, the common case is that StringToks points to one
1852 /// string.
1854 ExprResult
1855 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1856 assert(!StringToks.empty() && "Must have at least one string!");
1858 StringLiteralParser Literal(StringToks, PP);
1859 if (Literal.hadError)
1860 return ExprError();
1862 SmallVector<SourceLocation, 4> StringTokLocs;
1863 for (const Token &Tok : StringToks)
1864 StringTokLocs.push_back(Tok.getLocation());
1866 QualType CharTy = Context.CharTy;
1867 StringLiteral::StringKind Kind = StringLiteral::Ordinary;
1868 if (Literal.isWide()) {
1869 CharTy = Context.getWideCharType();
1870 Kind = StringLiteral::Wide;
1871 } else if (Literal.isUTF8()) {
1872 if (getLangOpts().Char8)
1873 CharTy = Context.Char8Ty;
1874 Kind = StringLiteral::UTF8;
1875 } else if (Literal.isUTF16()) {
1876 CharTy = Context.Char16Ty;
1877 Kind = StringLiteral::UTF16;
1878 } else if (Literal.isUTF32()) {
1879 CharTy = Context.Char32Ty;
1880 Kind = StringLiteral::UTF32;
1881 } else if (Literal.isPascal()) {
1882 CharTy = Context.UnsignedCharTy;
1885 // Warn on initializing an array of char from a u8 string literal; this
1886 // becomes ill-formed in C++2a.
1887 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1888 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1889 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1891 // Create removals for all 'u8' prefixes in the string literal(s). This
1892 // ensures C++2a compatibility (but may change the program behavior when
1893 // built by non-Clang compilers for which the execution character set is
1894 // not always UTF-8).
1895 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1896 SourceLocation RemovalDiagLoc;
1897 for (const Token &Tok : StringToks) {
1898 if (Tok.getKind() == tok::utf8_string_literal) {
1899 if (RemovalDiagLoc.isInvalid())
1900 RemovalDiagLoc = Tok.getLocation();
1901 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1902 Tok.getLocation(),
1903 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1904 getSourceManager(), getLangOpts())));
1907 Diag(RemovalDiagLoc, RemovalDiag);
1910 QualType StrTy =
1911 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1913 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1914 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1915 Kind, Literal.Pascal, StrTy,
1916 &StringTokLocs[0],
1917 StringTokLocs.size());
1918 if (Literal.getUDSuffix().empty())
1919 return Lit;
1921 // We're building a user-defined literal.
1922 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1923 SourceLocation UDSuffixLoc =
1924 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1925 Literal.getUDSuffixOffset());
1927 // Make sure we're allowed user-defined literals here.
1928 if (!UDLScope)
1929 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1931 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1932 // operator "" X (str, len)
1933 QualType SizeType = Context.getSizeType();
1935 DeclarationName OpName =
1936 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1937 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1938 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1940 QualType ArgTy[] = {
1941 Context.getArrayDecayedType(StrTy), SizeType
1944 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1945 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1946 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1947 /*AllowStringTemplatePack*/ true,
1948 /*DiagnoseMissing*/ true, Lit)) {
1950 case LOLR_Cooked: {
1951 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1952 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1953 StringTokLocs[0]);
1954 Expr *Args[] = { Lit, LenArg };
1956 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1959 case LOLR_Template: {
1960 TemplateArgumentListInfo ExplicitArgs;
1961 TemplateArgument Arg(Lit);
1962 TemplateArgumentLocInfo ArgInfo(Lit);
1963 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1964 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1965 &ExplicitArgs);
1968 case LOLR_StringTemplatePack: {
1969 TemplateArgumentListInfo ExplicitArgs;
1971 unsigned CharBits = Context.getIntWidth(CharTy);
1972 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1973 llvm::APSInt Value(CharBits, CharIsUnsigned);
1975 TemplateArgument TypeArg(CharTy);
1976 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1977 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1979 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1980 Value = Lit->getCodeUnit(I);
1981 TemplateArgument Arg(Context, Value, CharTy);
1982 TemplateArgumentLocInfo ArgInfo;
1983 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1985 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1986 &ExplicitArgs);
1988 case LOLR_Raw:
1989 case LOLR_ErrorNoDiagnostic:
1990 llvm_unreachable("unexpected literal operator lookup result");
1991 case LOLR_Error:
1992 return ExprError();
1994 llvm_unreachable("unexpected literal operator lookup result");
1997 DeclRefExpr *
1998 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1999 SourceLocation Loc,
2000 const CXXScopeSpec *SS) {
2001 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2002 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2005 DeclRefExpr *
2006 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2007 const DeclarationNameInfo &NameInfo,
2008 const CXXScopeSpec *SS, NamedDecl *FoundD,
2009 SourceLocation TemplateKWLoc,
2010 const TemplateArgumentListInfo *TemplateArgs) {
2011 NestedNameSpecifierLoc NNS =
2012 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
2013 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2014 TemplateArgs);
2017 // CUDA/HIP: Check whether a captured reference variable is referencing a
2018 // host variable in a device or host device lambda.
2019 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
2020 VarDecl *VD) {
2021 if (!S.getLangOpts().CUDA || !VD->hasInit())
2022 return false;
2023 assert(VD->getType()->isReferenceType());
2025 // Check whether the reference variable is referencing a host variable.
2026 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2027 if (!DRE)
2028 return false;
2029 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2030 if (!Referee || !Referee->hasGlobalStorage() ||
2031 Referee->hasAttr<CUDADeviceAttr>())
2032 return false;
2034 // Check whether the current function is a device or host device lambda.
2035 // Check whether the reference variable is a capture by getDeclContext()
2036 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2037 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2038 if (MD && MD->getParent()->isLambda() &&
2039 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2040 VD->getDeclContext() != MD)
2041 return true;
2043 return false;
2046 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2047 // A declaration named in an unevaluated operand never constitutes an odr-use.
2048 if (isUnevaluatedContext())
2049 return NOUR_Unevaluated;
2051 // C++2a [basic.def.odr]p4:
2052 // A variable x whose name appears as a potentially-evaluated expression e
2053 // is odr-used by e unless [...] x is a reference that is usable in
2054 // constant expressions.
2055 // CUDA/HIP:
2056 // If a reference variable referencing a host variable is captured in a
2057 // device or host device lambda, the value of the referee must be copied
2058 // to the capture and the reference variable must be treated as odr-use
2059 // since the value of the referee is not known at compile time and must
2060 // be loaded from the captured.
2061 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2062 if (VD->getType()->isReferenceType() &&
2063 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2064 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2065 VD->isUsableInConstantExpressions(Context))
2066 return NOUR_Constant;
2069 // All remaining non-variable cases constitute an odr-use. For variables, we
2070 // need to wait and see how the expression is used.
2071 return NOUR_None;
2074 /// BuildDeclRefExpr - Build an expression that references a
2075 /// declaration that does not require a closure capture.
2076 DeclRefExpr *
2077 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2078 const DeclarationNameInfo &NameInfo,
2079 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2080 SourceLocation TemplateKWLoc,
2081 const TemplateArgumentListInfo *TemplateArgs) {
2082 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2083 NeedToCaptureVariable(D, NameInfo.getLoc());
2085 DeclRefExpr *E = DeclRefExpr::Create(
2086 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2087 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2088 MarkDeclRefReferenced(E);
2090 // C++ [except.spec]p17:
2091 // An exception-specification is considered to be needed when:
2092 // - in an expression, the function is the unique lookup result or
2093 // the selected member of a set of overloaded functions.
2095 // We delay doing this until after we've built the function reference and
2096 // marked it as used so that:
2097 // a) if the function is defaulted, we get errors from defining it before /
2098 // instead of errors from computing its exception specification, and
2099 // b) if the function is a defaulted comparison, we can use the body we
2100 // build when defining it as input to the exception specification
2101 // computation rather than computing a new body.
2102 if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
2103 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2104 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2105 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2109 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2110 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2111 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2112 getCurFunction()->recordUseOfWeak(E);
2114 FieldDecl *FD = dyn_cast<FieldDecl>(D);
2115 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2116 FD = IFD->getAnonField();
2117 if (FD) {
2118 UnusedPrivateFields.remove(FD);
2119 // Just in case we're building an illegal pointer-to-member.
2120 if (FD->isBitField())
2121 E->setObjectKind(OK_BitField);
2124 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2125 // designates a bit-field.
2126 if (auto *BD = dyn_cast<BindingDecl>(D))
2127 if (auto *BE = BD->getBinding())
2128 E->setObjectKind(BE->getObjectKind());
2130 return E;
2133 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2134 /// possibly a list of template arguments.
2136 /// If this produces template arguments, it is permitted to call
2137 /// DecomposeTemplateName.
2139 /// This actually loses a lot of source location information for
2140 /// non-standard name kinds; we should consider preserving that in
2141 /// some way.
2142 void
2143 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2144 TemplateArgumentListInfo &Buffer,
2145 DeclarationNameInfo &NameInfo,
2146 const TemplateArgumentListInfo *&TemplateArgs) {
2147 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2148 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2149 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2151 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2152 Id.TemplateId->NumArgs);
2153 translateTemplateArguments(TemplateArgsPtr, Buffer);
2155 TemplateName TName = Id.TemplateId->Template.get();
2156 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2157 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2158 TemplateArgs = &Buffer;
2159 } else {
2160 NameInfo = GetNameFromUnqualifiedId(Id);
2161 TemplateArgs = nullptr;
2165 static void emitEmptyLookupTypoDiagnostic(
2166 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2167 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2168 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2169 DeclContext *Ctx =
2170 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2171 if (!TC) {
2172 // Emit a special diagnostic for failed member lookups.
2173 // FIXME: computing the declaration context might fail here (?)
2174 if (Ctx)
2175 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2176 << SS.getRange();
2177 else
2178 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2179 return;
2182 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2183 bool DroppedSpecifier =
2184 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2185 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2186 ? diag::note_implicit_param_decl
2187 : diag::note_previous_decl;
2188 if (!Ctx)
2189 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2190 SemaRef.PDiag(NoteID));
2191 else
2192 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2193 << Typo << Ctx << DroppedSpecifier
2194 << SS.getRange(),
2195 SemaRef.PDiag(NoteID));
2198 /// Diagnose a lookup that found results in an enclosing class during error
2199 /// recovery. This usually indicates that the results were found in a dependent
2200 /// base class that could not be searched as part of a template definition.
2201 /// Always issues a diagnostic (though this may be only a warning in MS
2202 /// compatibility mode).
2204 /// Return \c true if the error is unrecoverable, or \c false if the caller
2205 /// should attempt to recover using these lookup results.
2206 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) {
2207 // During a default argument instantiation the CurContext points
2208 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2209 // function parameter list, hence add an explicit check.
2210 bool isDefaultArgument =
2211 !CodeSynthesisContexts.empty() &&
2212 CodeSynthesisContexts.back().Kind ==
2213 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2214 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2215 bool isInstance = CurMethod && CurMethod->isInstance() &&
2216 R.getNamingClass() == CurMethod->getParent() &&
2217 !isDefaultArgument;
2219 // There are two ways we can find a class-scope declaration during template
2220 // instantiation that we did not find in the template definition: if it is a
2221 // member of a dependent base class, or if it is declared after the point of
2222 // use in the same class. Distinguish these by comparing the class in which
2223 // the member was found to the naming class of the lookup.
2224 unsigned DiagID = diag::err_found_in_dependent_base;
2225 unsigned NoteID = diag::note_member_declared_at;
2226 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2227 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2228 : diag::err_found_later_in_class;
2229 } else if (getLangOpts().MSVCCompat) {
2230 DiagID = diag::ext_found_in_dependent_base;
2231 NoteID = diag::note_dependent_member_use;
2234 if (isInstance) {
2235 // Give a code modification hint to insert 'this->'.
2236 Diag(R.getNameLoc(), DiagID)
2237 << R.getLookupName()
2238 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2239 CheckCXXThisCapture(R.getNameLoc());
2240 } else {
2241 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2242 // they're not shadowed).
2243 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2246 for (NamedDecl *D : R)
2247 Diag(D->getLocation(), NoteID);
2249 // Return true if we are inside a default argument instantiation
2250 // and the found name refers to an instance member function, otherwise
2251 // the caller will try to create an implicit member call and this is wrong
2252 // for default arguments.
2254 // FIXME: Is this special case necessary? We could allow the caller to
2255 // diagnose this.
2256 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2257 Diag(R.getNameLoc(), diag::err_member_call_without_object);
2258 return true;
2261 // Tell the callee to try to recover.
2262 return false;
2265 /// Diagnose an empty lookup.
2267 /// \return false if new lookup candidates were found
2268 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2269 CorrectionCandidateCallback &CCC,
2270 TemplateArgumentListInfo *ExplicitTemplateArgs,
2271 ArrayRef<Expr *> Args, TypoExpr **Out) {
2272 DeclarationName Name = R.getLookupName();
2274 unsigned diagnostic = diag::err_undeclared_var_use;
2275 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2276 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2277 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2278 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2279 diagnostic = diag::err_undeclared_use;
2280 diagnostic_suggest = diag::err_undeclared_use_suggest;
2283 // If the original lookup was an unqualified lookup, fake an
2284 // unqualified lookup. This is useful when (for example) the
2285 // original lookup would not have found something because it was a
2286 // dependent name.
2287 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2288 while (DC) {
2289 if (isa<CXXRecordDecl>(DC)) {
2290 LookupQualifiedName(R, DC);
2292 if (!R.empty()) {
2293 // Don't give errors about ambiguities in this lookup.
2294 R.suppressDiagnostics();
2296 // If there's a best viable function among the results, only mention
2297 // that one in the notes.
2298 OverloadCandidateSet Candidates(R.getNameLoc(),
2299 OverloadCandidateSet::CSK_Normal);
2300 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2301 OverloadCandidateSet::iterator Best;
2302 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2303 OR_Success) {
2304 R.clear();
2305 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2306 R.resolveKind();
2309 return DiagnoseDependentMemberLookup(R);
2312 R.clear();
2315 DC = DC->getLookupParent();
2318 // We didn't find anything, so try to correct for a typo.
2319 TypoCorrection Corrected;
2320 if (S && Out) {
2321 SourceLocation TypoLoc = R.getNameLoc();
2322 assert(!ExplicitTemplateArgs &&
2323 "Diagnosing an empty lookup with explicit template args!");
2324 *Out = CorrectTypoDelayed(
2325 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2326 [=](const TypoCorrection &TC) {
2327 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2328 diagnostic, diagnostic_suggest);
2330 nullptr, CTK_ErrorRecovery);
2331 if (*Out)
2332 return true;
2333 } else if (S &&
2334 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2335 S, &SS, CCC, CTK_ErrorRecovery))) {
2336 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2337 bool DroppedSpecifier =
2338 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2339 R.setLookupName(Corrected.getCorrection());
2341 bool AcceptableWithRecovery = false;
2342 bool AcceptableWithoutRecovery = false;
2343 NamedDecl *ND = Corrected.getFoundDecl();
2344 if (ND) {
2345 if (Corrected.isOverloaded()) {
2346 OverloadCandidateSet OCS(R.getNameLoc(),
2347 OverloadCandidateSet::CSK_Normal);
2348 OverloadCandidateSet::iterator Best;
2349 for (NamedDecl *CD : Corrected) {
2350 if (FunctionTemplateDecl *FTD =
2351 dyn_cast<FunctionTemplateDecl>(CD))
2352 AddTemplateOverloadCandidate(
2353 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2354 Args, OCS);
2355 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2356 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2357 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2358 Args, OCS);
2360 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2361 case OR_Success:
2362 ND = Best->FoundDecl;
2363 Corrected.setCorrectionDecl(ND);
2364 break;
2365 default:
2366 // FIXME: Arbitrarily pick the first declaration for the note.
2367 Corrected.setCorrectionDecl(ND);
2368 break;
2371 R.addDecl(ND);
2372 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2373 CXXRecordDecl *Record = nullptr;
2374 if (Corrected.getCorrectionSpecifier()) {
2375 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2376 Record = Ty->getAsCXXRecordDecl();
2378 if (!Record)
2379 Record = cast<CXXRecordDecl>(
2380 ND->getDeclContext()->getRedeclContext());
2381 R.setNamingClass(Record);
2384 auto *UnderlyingND = ND->getUnderlyingDecl();
2385 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2386 isa<FunctionTemplateDecl>(UnderlyingND);
2387 // FIXME: If we ended up with a typo for a type name or
2388 // Objective-C class name, we're in trouble because the parser
2389 // is in the wrong place to recover. Suggest the typo
2390 // correction, but don't make it a fix-it since we're not going
2391 // to recover well anyway.
2392 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2393 getAsTypeTemplateDecl(UnderlyingND) ||
2394 isa<ObjCInterfaceDecl>(UnderlyingND);
2395 } else {
2396 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2397 // because we aren't able to recover.
2398 AcceptableWithoutRecovery = true;
2401 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2402 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2403 ? diag::note_implicit_param_decl
2404 : diag::note_previous_decl;
2405 if (SS.isEmpty())
2406 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2407 PDiag(NoteID), AcceptableWithRecovery);
2408 else
2409 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2410 << Name << computeDeclContext(SS, false)
2411 << DroppedSpecifier << SS.getRange(),
2412 PDiag(NoteID), AcceptableWithRecovery);
2414 // Tell the callee whether to try to recover.
2415 return !AcceptableWithRecovery;
2418 R.clear();
2420 // Emit a special diagnostic for failed member lookups.
2421 // FIXME: computing the declaration context might fail here (?)
2422 if (!SS.isEmpty()) {
2423 Diag(R.getNameLoc(), diag::err_no_member)
2424 << Name << computeDeclContext(SS, false)
2425 << SS.getRange();
2426 return true;
2429 // Give up, we can't recover.
2430 Diag(R.getNameLoc(), diagnostic) << Name;
2431 return true;
2434 /// In Microsoft mode, if we are inside a template class whose parent class has
2435 /// dependent base classes, and we can't resolve an unqualified identifier, then
2436 /// assume the identifier is a member of a dependent base class. We can only
2437 /// recover successfully in static methods, instance methods, and other contexts
2438 /// where 'this' is available. This doesn't precisely match MSVC's
2439 /// instantiation model, but it's close enough.
2440 static Expr *
2441 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2442 DeclarationNameInfo &NameInfo,
2443 SourceLocation TemplateKWLoc,
2444 const TemplateArgumentListInfo *TemplateArgs) {
2445 // Only try to recover from lookup into dependent bases in static methods or
2446 // contexts where 'this' is available.
2447 QualType ThisType = S.getCurrentThisType();
2448 const CXXRecordDecl *RD = nullptr;
2449 if (!ThisType.isNull())
2450 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2451 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2452 RD = MD->getParent();
2453 if (!RD || !RD->hasAnyDependentBases())
2454 return nullptr;
2456 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2457 // is available, suggest inserting 'this->' as a fixit.
2458 SourceLocation Loc = NameInfo.getLoc();
2459 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2460 DB << NameInfo.getName() << RD;
2462 if (!ThisType.isNull()) {
2463 DB << FixItHint::CreateInsertion(Loc, "this->");
2464 return CXXDependentScopeMemberExpr::Create(
2465 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2466 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2467 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2470 // Synthesize a fake NNS that points to the derived class. This will
2471 // perform name lookup during template instantiation.
2472 CXXScopeSpec SS;
2473 auto *NNS =
2474 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2475 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2476 return DependentScopeDeclRefExpr::Create(
2477 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2478 TemplateArgs);
2481 ExprResult
2482 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2483 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2484 bool HasTrailingLParen, bool IsAddressOfOperand,
2485 CorrectionCandidateCallback *CCC,
2486 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2487 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2488 "cannot be direct & operand and have a trailing lparen");
2489 if (SS.isInvalid())
2490 return ExprError();
2492 TemplateArgumentListInfo TemplateArgsBuffer;
2494 // Decompose the UnqualifiedId into the following data.
2495 DeclarationNameInfo NameInfo;
2496 const TemplateArgumentListInfo *TemplateArgs;
2497 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2499 DeclarationName Name = NameInfo.getName();
2500 IdentifierInfo *II = Name.getAsIdentifierInfo();
2501 SourceLocation NameLoc = NameInfo.getLoc();
2503 if (II && II->isEditorPlaceholder()) {
2504 // FIXME: When typed placeholders are supported we can create a typed
2505 // placeholder expression node.
2506 return ExprError();
2509 // C++ [temp.dep.expr]p3:
2510 // An id-expression is type-dependent if it contains:
2511 // -- an identifier that was declared with a dependent type,
2512 // (note: handled after lookup)
2513 // -- a template-id that is dependent,
2514 // (note: handled in BuildTemplateIdExpr)
2515 // -- a conversion-function-id that specifies a dependent type,
2516 // -- a nested-name-specifier that contains a class-name that
2517 // names a dependent type.
2518 // Determine whether this is a member of an unknown specialization;
2519 // we need to handle these differently.
2520 bool DependentID = false;
2521 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2522 Name.getCXXNameType()->isDependentType()) {
2523 DependentID = true;
2524 } else if (SS.isSet()) {
2525 if (DeclContext *DC = computeDeclContext(SS, false)) {
2526 if (RequireCompleteDeclContext(SS, DC))
2527 return ExprError();
2528 } else {
2529 DependentID = true;
2533 if (DependentID)
2534 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2535 IsAddressOfOperand, TemplateArgs);
2537 // Perform the required lookup.
2538 LookupResult R(*this, NameInfo,
2539 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2540 ? LookupObjCImplicitSelfParam
2541 : LookupOrdinaryName);
2542 if (TemplateKWLoc.isValid() || TemplateArgs) {
2543 // Lookup the template name again to correctly establish the context in
2544 // which it was found. This is really unfortunate as we already did the
2545 // lookup to determine that it was a template name in the first place. If
2546 // this becomes a performance hit, we can work harder to preserve those
2547 // results until we get here but it's likely not worth it.
2548 bool MemberOfUnknownSpecialization;
2549 AssumedTemplateKind AssumedTemplate;
2550 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2551 MemberOfUnknownSpecialization, TemplateKWLoc,
2552 &AssumedTemplate))
2553 return ExprError();
2555 if (MemberOfUnknownSpecialization ||
2556 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2557 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2558 IsAddressOfOperand, TemplateArgs);
2559 } else {
2560 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2561 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2563 // If the result might be in a dependent base class, this is a dependent
2564 // id-expression.
2565 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2566 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2567 IsAddressOfOperand, TemplateArgs);
2569 // If this reference is in an Objective-C method, then we need to do
2570 // some special Objective-C lookup, too.
2571 if (IvarLookupFollowUp) {
2572 ExprResult E(LookupInObjCMethod(R, S, II, true));
2573 if (E.isInvalid())
2574 return ExprError();
2576 if (Expr *Ex = E.getAs<Expr>())
2577 return Ex;
2581 if (R.isAmbiguous())
2582 return ExprError();
2584 // This could be an implicitly declared function reference if the language
2585 // mode allows it as a feature.
2586 if (R.empty() && HasTrailingLParen && II &&
2587 getLangOpts().implicitFunctionsAllowed()) {
2588 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2589 if (D) R.addDecl(D);
2592 // Determine whether this name might be a candidate for
2593 // argument-dependent lookup.
2594 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2596 if (R.empty() && !ADL) {
2597 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2598 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2599 TemplateKWLoc, TemplateArgs))
2600 return E;
2603 // Don't diagnose an empty lookup for inline assembly.
2604 if (IsInlineAsmIdentifier)
2605 return ExprError();
2607 // If this name wasn't predeclared and if this is not a function
2608 // call, diagnose the problem.
2609 TypoExpr *TE = nullptr;
2610 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2611 : nullptr);
2612 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2613 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2614 "Typo correction callback misconfigured");
2615 if (CCC) {
2616 // Make sure the callback knows what the typo being diagnosed is.
2617 CCC->setTypoName(II);
2618 if (SS.isValid())
2619 CCC->setTypoNNS(SS.getScopeRep());
2621 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2622 // a template name, but we happen to have always already looked up the name
2623 // before we get here if it must be a template name.
2624 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2625 None, &TE)) {
2626 if (TE && KeywordReplacement) {
2627 auto &State = getTypoExprState(TE);
2628 auto BestTC = State.Consumer->getNextCorrection();
2629 if (BestTC.isKeyword()) {
2630 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2631 if (State.DiagHandler)
2632 State.DiagHandler(BestTC);
2633 KeywordReplacement->startToken();
2634 KeywordReplacement->setKind(II->getTokenID());
2635 KeywordReplacement->setIdentifierInfo(II);
2636 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2637 // Clean up the state associated with the TypoExpr, since it has
2638 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2639 clearDelayedTypo(TE);
2640 // Signal that a correction to a keyword was performed by returning a
2641 // valid-but-null ExprResult.
2642 return (Expr*)nullptr;
2644 State.Consumer->resetCorrectionStream();
2646 return TE ? TE : ExprError();
2649 assert(!R.empty() &&
2650 "DiagnoseEmptyLookup returned false but added no results");
2652 // If we found an Objective-C instance variable, let
2653 // LookupInObjCMethod build the appropriate expression to
2654 // reference the ivar.
2655 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2656 R.clear();
2657 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2658 // In a hopelessly buggy code, Objective-C instance variable
2659 // lookup fails and no expression will be built to reference it.
2660 if (!E.isInvalid() && !E.get())
2661 return ExprError();
2662 return E;
2666 // This is guaranteed from this point on.
2667 assert(!R.empty() || ADL);
2669 // Check whether this might be a C++ implicit instance member access.
2670 // C++ [class.mfct.non-static]p3:
2671 // When an id-expression that is not part of a class member access
2672 // syntax and not used to form a pointer to member is used in the
2673 // body of a non-static member function of class X, if name lookup
2674 // resolves the name in the id-expression to a non-static non-type
2675 // member of some class C, the id-expression is transformed into a
2676 // class member access expression using (*this) as the
2677 // postfix-expression to the left of the . operator.
2679 // But we don't actually need to do this for '&' operands if R
2680 // resolved to a function or overloaded function set, because the
2681 // expression is ill-formed if it actually works out to be a
2682 // non-static member function:
2684 // C++ [expr.ref]p4:
2685 // Otherwise, if E1.E2 refers to a non-static member function. . .
2686 // [t]he expression can be used only as the left-hand operand of a
2687 // member function call.
2689 // There are other safeguards against such uses, but it's important
2690 // to get this right here so that we don't end up making a
2691 // spuriously dependent expression if we're inside a dependent
2692 // instance method.
2693 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2694 bool MightBeImplicitMember;
2695 if (!IsAddressOfOperand)
2696 MightBeImplicitMember = true;
2697 else if (!SS.isEmpty())
2698 MightBeImplicitMember = false;
2699 else if (R.isOverloadedResult())
2700 MightBeImplicitMember = false;
2701 else if (R.isUnresolvableResult())
2702 MightBeImplicitMember = true;
2703 else
2704 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2705 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2706 isa<MSPropertyDecl>(R.getFoundDecl());
2708 if (MightBeImplicitMember)
2709 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2710 R, TemplateArgs, S);
2713 if (TemplateArgs || TemplateKWLoc.isValid()) {
2715 // In C++1y, if this is a variable template id, then check it
2716 // in BuildTemplateIdExpr().
2717 // The single lookup result must be a variable template declaration.
2718 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2719 Id.TemplateId->Kind == TNK_Var_template) {
2720 assert(R.getAsSingle<VarTemplateDecl>() &&
2721 "There should only be one declaration found.");
2724 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2727 return BuildDeclarationNameExpr(SS, R, ADL);
2730 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2731 /// declaration name, generally during template instantiation.
2732 /// There's a large number of things which don't need to be done along
2733 /// this path.
2734 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2735 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2736 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2737 DeclContext *DC = computeDeclContext(SS, false);
2738 if (!DC)
2739 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2740 NameInfo, /*TemplateArgs=*/nullptr);
2742 if (RequireCompleteDeclContext(SS, DC))
2743 return ExprError();
2745 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2746 LookupQualifiedName(R, DC);
2748 if (R.isAmbiguous())
2749 return ExprError();
2751 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2752 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2753 NameInfo, /*TemplateArgs=*/nullptr);
2755 if (R.empty()) {
2756 // Don't diagnose problems with invalid record decl, the secondary no_member
2757 // diagnostic during template instantiation is likely bogus, e.g. if a class
2758 // is invalid because it's derived from an invalid base class, then missing
2759 // members were likely supposed to be inherited.
2760 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2761 if (CD->isInvalidDecl())
2762 return ExprError();
2763 Diag(NameInfo.getLoc(), diag::err_no_member)
2764 << NameInfo.getName() << DC << SS.getRange();
2765 return ExprError();
2768 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2769 // Diagnose a missing typename if this resolved unambiguously to a type in
2770 // a dependent context. If we can recover with a type, downgrade this to
2771 // a warning in Microsoft compatibility mode.
2772 unsigned DiagID = diag::err_typename_missing;
2773 if (RecoveryTSI && getLangOpts().MSVCCompat)
2774 DiagID = diag::ext_typename_missing;
2775 SourceLocation Loc = SS.getBeginLoc();
2776 auto D = Diag(Loc, DiagID);
2777 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2778 << SourceRange(Loc, NameInfo.getEndLoc());
2780 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2781 // context.
2782 if (!RecoveryTSI)
2783 return ExprError();
2785 // Only issue the fixit if we're prepared to recover.
2786 D << FixItHint::CreateInsertion(Loc, "typename ");
2788 // Recover by pretending this was an elaborated type.
2789 QualType Ty = Context.getTypeDeclType(TD);
2790 TypeLocBuilder TLB;
2791 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2793 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2794 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2795 QTL.setElaboratedKeywordLoc(SourceLocation());
2796 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2798 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2800 return ExprEmpty();
2803 // Defend against this resolving to an implicit member access. We usually
2804 // won't get here if this might be a legitimate a class member (we end up in
2805 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2806 // a pointer-to-member or in an unevaluated context in C++11.
2807 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2808 return BuildPossibleImplicitMemberExpr(SS,
2809 /*TemplateKWLoc=*/SourceLocation(),
2810 R, /*TemplateArgs=*/nullptr, S);
2812 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2815 /// The parser has read a name in, and Sema has detected that we're currently
2816 /// inside an ObjC method. Perform some additional checks and determine if we
2817 /// should form a reference to an ivar.
2819 /// Ideally, most of this would be done by lookup, but there's
2820 /// actually quite a lot of extra work involved.
2821 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2822 IdentifierInfo *II) {
2823 SourceLocation Loc = Lookup.getNameLoc();
2824 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2826 // Check for error condition which is already reported.
2827 if (!CurMethod)
2828 return DeclResult(true);
2830 // There are two cases to handle here. 1) scoped lookup could have failed,
2831 // in which case we should look for an ivar. 2) scoped lookup could have
2832 // found a decl, but that decl is outside the current instance method (i.e.
2833 // a global variable). In these two cases, we do a lookup for an ivar with
2834 // this name, if the lookup sucedes, we replace it our current decl.
2836 // If we're in a class method, we don't normally want to look for
2837 // ivars. But if we don't find anything else, and there's an
2838 // ivar, that's an error.
2839 bool IsClassMethod = CurMethod->isClassMethod();
2841 bool LookForIvars;
2842 if (Lookup.empty())
2843 LookForIvars = true;
2844 else if (IsClassMethod)
2845 LookForIvars = false;
2846 else
2847 LookForIvars = (Lookup.isSingleResult() &&
2848 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2849 ObjCInterfaceDecl *IFace = nullptr;
2850 if (LookForIvars) {
2851 IFace = CurMethod->getClassInterface();
2852 ObjCInterfaceDecl *ClassDeclared;
2853 ObjCIvarDecl *IV = nullptr;
2854 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2855 // Diagnose using an ivar in a class method.
2856 if (IsClassMethod) {
2857 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2858 return DeclResult(true);
2861 // Diagnose the use of an ivar outside of the declaring class.
2862 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2863 !declaresSameEntity(ClassDeclared, IFace) &&
2864 !getLangOpts().DebuggerSupport)
2865 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2867 // Success.
2868 return IV;
2870 } else if (CurMethod->isInstanceMethod()) {
2871 // We should warn if a local variable hides an ivar.
2872 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2873 ObjCInterfaceDecl *ClassDeclared;
2874 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2875 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2876 declaresSameEntity(IFace, ClassDeclared))
2877 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2880 } else if (Lookup.isSingleResult() &&
2881 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2882 // If accessing a stand-alone ivar in a class method, this is an error.
2883 if (const ObjCIvarDecl *IV =
2884 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2885 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2886 return DeclResult(true);
2890 // Didn't encounter an error, didn't find an ivar.
2891 return DeclResult(false);
2894 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2895 ObjCIvarDecl *IV) {
2896 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2897 assert(CurMethod && CurMethod->isInstanceMethod() &&
2898 "should not reference ivar from this context");
2900 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2901 assert(IFace && "should not reference ivar from this context");
2903 // If we're referencing an invalid decl, just return this as a silent
2904 // error node. The error diagnostic was already emitted on the decl.
2905 if (IV->isInvalidDecl())
2906 return ExprError();
2908 // Check if referencing a field with __attribute__((deprecated)).
2909 if (DiagnoseUseOfDecl(IV, Loc))
2910 return ExprError();
2912 // FIXME: This should use a new expr for a direct reference, don't
2913 // turn this into Self->ivar, just return a BareIVarExpr or something.
2914 IdentifierInfo &II = Context.Idents.get("self");
2915 UnqualifiedId SelfName;
2916 SelfName.setImplicitSelfParam(&II);
2917 CXXScopeSpec SelfScopeSpec;
2918 SourceLocation TemplateKWLoc;
2919 ExprResult SelfExpr =
2920 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2921 /*HasTrailingLParen=*/false,
2922 /*IsAddressOfOperand=*/false);
2923 if (SelfExpr.isInvalid())
2924 return ExprError();
2926 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2927 if (SelfExpr.isInvalid())
2928 return ExprError();
2930 MarkAnyDeclReferenced(Loc, IV, true);
2932 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2933 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2934 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2935 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2937 ObjCIvarRefExpr *Result = new (Context)
2938 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2939 IV->getLocation(), SelfExpr.get(), true, true);
2941 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2942 if (!isUnevaluatedContext() &&
2943 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2944 getCurFunction()->recordUseOfWeak(Result);
2946 if (getLangOpts().ObjCAutoRefCount && !isUnevaluatedContext())
2947 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2948 ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2950 return Result;
2953 /// The parser has read a name in, and Sema has detected that we're currently
2954 /// inside an ObjC method. Perform some additional checks and determine if we
2955 /// should form a reference to an ivar. If so, build an expression referencing
2956 /// that ivar.
2957 ExprResult
2958 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2959 IdentifierInfo *II, bool AllowBuiltinCreation) {
2960 // FIXME: Integrate this lookup step into LookupParsedName.
2961 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2962 if (Ivar.isInvalid())
2963 return ExprError();
2964 if (Ivar.isUsable())
2965 return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2966 cast<ObjCIvarDecl>(Ivar.get()));
2968 if (Lookup.empty() && II && AllowBuiltinCreation)
2969 LookupBuiltin(Lookup);
2971 // Sentinel value saying that we didn't do anything special.
2972 return ExprResult(false);
2975 /// Cast a base object to a member's actual type.
2977 /// There are two relevant checks:
2979 /// C++ [class.access.base]p7:
2981 /// If a class member access operator [...] is used to access a non-static
2982 /// data member or non-static member function, the reference is ill-formed if
2983 /// the left operand [...] cannot be implicitly converted to a pointer to the
2984 /// naming class of the right operand.
2986 /// C++ [expr.ref]p7:
2988 /// If E2 is a non-static data member or a non-static member function, the
2989 /// program is ill-formed if the class of which E2 is directly a member is an
2990 /// ambiguous base (11.8) of the naming class (11.9.3) of E2.
2992 /// Note that the latter check does not consider access; the access of the
2993 /// "real" base class is checked as appropriate when checking the access of the
2994 /// member name.
2995 ExprResult
2996 Sema::PerformObjectMemberConversion(Expr *From,
2997 NestedNameSpecifier *Qualifier,
2998 NamedDecl *FoundDecl,
2999 NamedDecl *Member) {
3000 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3001 if (!RD)
3002 return From;
3004 QualType DestRecordType;
3005 QualType DestType;
3006 QualType FromRecordType;
3007 QualType FromType = From->getType();
3008 bool PointerConversions = false;
3009 if (isa<FieldDecl>(Member)) {
3010 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
3011 auto FromPtrType = FromType->getAs<PointerType>();
3012 DestRecordType = Context.getAddrSpaceQualType(
3013 DestRecordType, FromPtrType
3014 ? FromType->getPointeeType().getAddressSpace()
3015 : FromType.getAddressSpace());
3017 if (FromPtrType) {
3018 DestType = Context.getPointerType(DestRecordType);
3019 FromRecordType = FromPtrType->getPointeeType();
3020 PointerConversions = true;
3021 } else {
3022 DestType = DestRecordType;
3023 FromRecordType = FromType;
3025 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
3026 if (Method->isStatic())
3027 return From;
3029 DestType = Method->getThisType();
3030 DestRecordType = DestType->getPointeeType();
3032 if (FromType->getAs<PointerType>()) {
3033 FromRecordType = FromType->getPointeeType();
3034 PointerConversions = true;
3035 } else {
3036 FromRecordType = FromType;
3037 DestType = DestRecordType;
3040 LangAS FromAS = FromRecordType.getAddressSpace();
3041 LangAS DestAS = DestRecordType.getAddressSpace();
3042 if (FromAS != DestAS) {
3043 QualType FromRecordTypeWithoutAS =
3044 Context.removeAddrSpaceQualType(FromRecordType);
3045 QualType FromTypeWithDestAS =
3046 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3047 if (PointerConversions)
3048 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3049 From = ImpCastExprToType(From, FromTypeWithDestAS,
3050 CK_AddressSpaceConversion, From->getValueKind())
3051 .get();
3053 } else {
3054 // No conversion necessary.
3055 return From;
3058 if (DestType->isDependentType() || FromType->isDependentType())
3059 return From;
3061 // If the unqualified types are the same, no conversion is necessary.
3062 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3063 return From;
3065 SourceRange FromRange = From->getSourceRange();
3066 SourceLocation FromLoc = FromRange.getBegin();
3068 ExprValueKind VK = From->getValueKind();
3070 // C++ [class.member.lookup]p8:
3071 // [...] Ambiguities can often be resolved by qualifying a name with its
3072 // class name.
3074 // If the member was a qualified name and the qualified referred to a
3075 // specific base subobject type, we'll cast to that intermediate type
3076 // first and then to the object in which the member is declared. That allows
3077 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3079 // class Base { public: int x; };
3080 // class Derived1 : public Base { };
3081 // class Derived2 : public Base { };
3082 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3084 // void VeryDerived::f() {
3085 // x = 17; // error: ambiguous base subobjects
3086 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3087 // }
3088 if (Qualifier && Qualifier->getAsType()) {
3089 QualType QType = QualType(Qualifier->getAsType(), 0);
3090 assert(QType->isRecordType() && "lookup done with non-record type");
3092 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3094 // In C++98, the qualifier type doesn't actually have to be a base
3095 // type of the object type, in which case we just ignore it.
3096 // Otherwise build the appropriate casts.
3097 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3098 CXXCastPath BasePath;
3099 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3100 FromLoc, FromRange, &BasePath))
3101 return ExprError();
3103 if (PointerConversions)
3104 QType = Context.getPointerType(QType);
3105 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3106 VK, &BasePath).get();
3108 FromType = QType;
3109 FromRecordType = QRecordType;
3111 // If the qualifier type was the same as the destination type,
3112 // we're done.
3113 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3114 return From;
3118 CXXCastPath BasePath;
3119 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3120 FromLoc, FromRange, &BasePath,
3121 /*IgnoreAccess=*/true))
3122 return ExprError();
3124 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3125 VK, &BasePath);
3128 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3129 const LookupResult &R,
3130 bool HasTrailingLParen) {
3131 // Only when used directly as the postfix-expression of a call.
3132 if (!HasTrailingLParen)
3133 return false;
3135 // Never if a scope specifier was provided.
3136 if (SS.isSet())
3137 return false;
3139 // Only in C++ or ObjC++.
3140 if (!getLangOpts().CPlusPlus)
3141 return false;
3143 // Turn off ADL when we find certain kinds of declarations during
3144 // normal lookup:
3145 for (NamedDecl *D : R) {
3146 // C++0x [basic.lookup.argdep]p3:
3147 // -- a declaration of a class member
3148 // Since using decls preserve this property, we check this on the
3149 // original decl.
3150 if (D->isCXXClassMember())
3151 return false;
3153 // C++0x [basic.lookup.argdep]p3:
3154 // -- a block-scope function declaration that is not a
3155 // using-declaration
3156 // NOTE: we also trigger this for function templates (in fact, we
3157 // don't check the decl type at all, since all other decl types
3158 // turn off ADL anyway).
3159 if (isa<UsingShadowDecl>(D))
3160 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3161 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3162 return false;
3164 // C++0x [basic.lookup.argdep]p3:
3165 // -- a declaration that is neither a function or a function
3166 // template
3167 // And also for builtin functions.
3168 if (isa<FunctionDecl>(D)) {
3169 FunctionDecl *FDecl = cast<FunctionDecl>(D);
3171 // But also builtin functions.
3172 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3173 return false;
3174 } else if (!isa<FunctionTemplateDecl>(D))
3175 return false;
3178 return true;
3182 /// Diagnoses obvious problems with the use of the given declaration
3183 /// as an expression. This is only actually called for lookups that
3184 /// were not overloaded, and it doesn't promise that the declaration
3185 /// will in fact be used.
3186 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3187 if (D->isInvalidDecl())
3188 return true;
3190 if (isa<TypedefNameDecl>(D)) {
3191 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3192 return true;
3195 if (isa<ObjCInterfaceDecl>(D)) {
3196 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3197 return true;
3200 if (isa<NamespaceDecl>(D)) {
3201 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3202 return true;
3205 return false;
3208 // Certain multiversion types should be treated as overloaded even when there is
3209 // only one result.
3210 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3211 assert(R.isSingleResult() && "Expected only a single result");
3212 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3213 return FD &&
3214 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3217 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3218 LookupResult &R, bool NeedsADL,
3219 bool AcceptInvalidDecl) {
3220 // If this is a single, fully-resolved result and we don't need ADL,
3221 // just build an ordinary singleton decl ref.
3222 if (!NeedsADL && R.isSingleResult() &&
3223 !R.getAsSingle<FunctionTemplateDecl>() &&
3224 !ShouldLookupResultBeMultiVersionOverload(R))
3225 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3226 R.getRepresentativeDecl(), nullptr,
3227 AcceptInvalidDecl);
3229 // We only need to check the declaration if there's exactly one
3230 // result, because in the overloaded case the results can only be
3231 // functions and function templates.
3232 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3233 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3234 return ExprError();
3236 // Otherwise, just build an unresolved lookup expression. Suppress
3237 // any lookup-related diagnostics; we'll hash these out later, when
3238 // we've picked a target.
3239 R.suppressDiagnostics();
3241 UnresolvedLookupExpr *ULE
3242 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3243 SS.getWithLocInContext(Context),
3244 R.getLookupNameInfo(),
3245 NeedsADL, R.isOverloadedResult(),
3246 R.begin(), R.end());
3248 return ULE;
3251 static void diagnoseUncapturableValueReferenceOrBinding(Sema &S,
3252 SourceLocation loc,
3253 ValueDecl *var);
3255 /// Complete semantic analysis for a reference to the given declaration.
3256 ExprResult Sema::BuildDeclarationNameExpr(
3257 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3258 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3259 bool AcceptInvalidDecl) {
3260 assert(D && "Cannot refer to a NULL declaration");
3261 assert(!isa<FunctionTemplateDecl>(D) &&
3262 "Cannot refer unambiguously to a function template");
3264 SourceLocation Loc = NameInfo.getLoc();
3265 if (CheckDeclInExpr(*this, Loc, D)) {
3266 // Recovery from invalid cases (e.g. D is an invalid Decl).
3267 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3268 // diagnostics, as invalid decls use int as a fallback type.
3269 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3272 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3273 // Specifically diagnose references to class templates that are missing
3274 // a template argument list.
3275 diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3276 return ExprError();
3279 // Make sure that we're referring to a value.
3280 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3281 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3282 Diag(D->getLocation(), diag::note_declared_at);
3283 return ExprError();
3286 // Check whether this declaration can be used. Note that we suppress
3287 // this check when we're going to perform argument-dependent lookup
3288 // on this function name, because this might not be the function
3289 // that overload resolution actually selects.
3290 if (DiagnoseUseOfDecl(D, Loc))
3291 return ExprError();
3293 auto *VD = cast<ValueDecl>(D);
3295 // Only create DeclRefExpr's for valid Decl's.
3296 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3297 return ExprError();
3299 // Handle members of anonymous structs and unions. If we got here,
3300 // and the reference is to a class member indirect field, then this
3301 // must be the subject of a pointer-to-member expression.
3302 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3303 if (!indirectField->isCXXClassMember())
3304 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3305 indirectField);
3307 QualType type = VD->getType();
3308 if (type.isNull())
3309 return ExprError();
3310 ExprValueKind valueKind = VK_PRValue;
3312 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3313 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3314 // is expanded by some outer '...' in the context of the use.
3315 type = type.getNonPackExpansionType();
3317 switch (D->getKind()) {
3318 // Ignore all the non-ValueDecl kinds.
3319 #define ABSTRACT_DECL(kind)
3320 #define VALUE(type, base)
3321 #define DECL(type, base) case Decl::type:
3322 #include "clang/AST/DeclNodes.inc"
3323 llvm_unreachable("invalid value decl kind");
3325 // These shouldn't make it here.
3326 case Decl::ObjCAtDefsField:
3327 llvm_unreachable("forming non-member reference to ivar?");
3329 // Enum constants are always r-values and never references.
3330 // Unresolved using declarations are dependent.
3331 case Decl::EnumConstant:
3332 case Decl::UnresolvedUsingValue:
3333 case Decl::OMPDeclareReduction:
3334 case Decl::OMPDeclareMapper:
3335 valueKind = VK_PRValue;
3336 break;
3338 // Fields and indirect fields that got here must be for
3339 // pointer-to-member expressions; we just call them l-values for
3340 // internal consistency, because this subexpression doesn't really
3341 // exist in the high-level semantics.
3342 case Decl::Field:
3343 case Decl::IndirectField:
3344 case Decl::ObjCIvar:
3345 assert(getLangOpts().CPlusPlus && "building reference to field in C?");
3347 // These can't have reference type in well-formed programs, but
3348 // for internal consistency we do this anyway.
3349 type = type.getNonReferenceType();
3350 valueKind = VK_LValue;
3351 break;
3353 // Non-type template parameters are either l-values or r-values
3354 // depending on the type.
3355 case Decl::NonTypeTemplateParm: {
3356 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3357 type = reftype->getPointeeType();
3358 valueKind = VK_LValue; // even if the parameter is an r-value reference
3359 break;
3362 // [expr.prim.id.unqual]p2:
3363 // If the entity is a template parameter object for a template
3364 // parameter of type T, the type of the expression is const T.
3365 // [...] The expression is an lvalue if the entity is a [...] template
3366 // parameter object.
3367 if (type->isRecordType()) {
3368 type = type.getUnqualifiedType().withConst();
3369 valueKind = VK_LValue;
3370 break;
3373 // For non-references, we need to strip qualifiers just in case
3374 // the template parameter was declared as 'const int' or whatever.
3375 valueKind = VK_PRValue;
3376 type = type.getUnqualifiedType();
3377 break;
3380 case Decl::Var:
3381 case Decl::VarTemplateSpecialization:
3382 case Decl::VarTemplatePartialSpecialization:
3383 case Decl::Decomposition:
3384 case Decl::OMPCapturedExpr:
3385 // In C, "extern void blah;" is valid and is an r-value.
3386 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3387 type->isVoidType()) {
3388 valueKind = VK_PRValue;
3389 break;
3391 [[fallthrough]];
3393 case Decl::ImplicitParam:
3394 case Decl::ParmVar: {
3395 // These are always l-values.
3396 valueKind = VK_LValue;
3397 type = type.getNonReferenceType();
3399 // FIXME: Does the addition of const really only apply in
3400 // potentially-evaluated contexts? Since the variable isn't actually
3401 // captured in an unevaluated context, it seems that the answer is no.
3402 if (!isUnevaluatedContext()) {
3403 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3404 if (!CapturedType.isNull())
3405 type = CapturedType;
3408 break;
3411 case Decl::Binding:
3412 // These are always lvalues.
3413 valueKind = VK_LValue;
3414 type = type.getNonReferenceType();
3415 break;
3417 case Decl::Function: {
3418 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3419 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3420 type = Context.BuiltinFnTy;
3421 valueKind = VK_PRValue;
3422 break;
3426 const FunctionType *fty = type->castAs<FunctionType>();
3428 // If we're referring to a function with an __unknown_anytype
3429 // result type, make the entire expression __unknown_anytype.
3430 if (fty->getReturnType() == Context.UnknownAnyTy) {
3431 type = Context.UnknownAnyTy;
3432 valueKind = VK_PRValue;
3433 break;
3436 // Functions are l-values in C++.
3437 if (getLangOpts().CPlusPlus) {
3438 valueKind = VK_LValue;
3439 break;
3442 // C99 DR 316 says that, if a function type comes from a
3443 // function definition (without a prototype), that type is only
3444 // used for checking compatibility. Therefore, when referencing
3445 // the function, we pretend that we don't have the full function
3446 // type.
3447 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3448 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3449 fty->getExtInfo());
3451 // Functions are r-values in C.
3452 valueKind = VK_PRValue;
3453 break;
3456 case Decl::CXXDeductionGuide:
3457 llvm_unreachable("building reference to deduction guide");
3459 case Decl::MSProperty:
3460 case Decl::MSGuid:
3461 case Decl::TemplateParamObject:
3462 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3463 // capture in OpenMP, or duplicated between host and device?
3464 valueKind = VK_LValue;
3465 break;
3467 case Decl::UnnamedGlobalConstant:
3468 valueKind = VK_LValue;
3469 break;
3471 case Decl::CXXMethod:
3472 // If we're referring to a method with an __unknown_anytype
3473 // result type, make the entire expression __unknown_anytype.
3474 // This should only be possible with a type written directly.
3475 if (const FunctionProtoType *proto =
3476 dyn_cast<FunctionProtoType>(VD->getType()))
3477 if (proto->getReturnType() == Context.UnknownAnyTy) {
3478 type = Context.UnknownAnyTy;
3479 valueKind = VK_PRValue;
3480 break;
3483 // C++ methods are l-values if static, r-values if non-static.
3484 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3485 valueKind = VK_LValue;
3486 break;
3488 [[fallthrough]];
3490 case Decl::CXXConversion:
3491 case Decl::CXXDestructor:
3492 case Decl::CXXConstructor:
3493 valueKind = VK_PRValue;
3494 break;
3497 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3498 /*FIXME: TemplateKWLoc*/ SourceLocation(),
3499 TemplateArgs);
3502 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3503 SmallString<32> &Target) {
3504 Target.resize(CharByteWidth * (Source.size() + 1));
3505 char *ResultPtr = &Target[0];
3506 const llvm::UTF8 *ErrorPtr;
3507 bool success =
3508 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3509 (void)success;
3510 assert(success);
3511 Target.resize(ResultPtr - &Target[0]);
3514 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3515 PredefinedExpr::IdentKind IK) {
3516 // Pick the current block, lambda, captured statement or function.
3517 Decl *currentDecl = nullptr;
3518 if (const BlockScopeInfo *BSI = getCurBlock())
3519 currentDecl = BSI->TheDecl;
3520 else if (const LambdaScopeInfo *LSI = getCurLambda())
3521 currentDecl = LSI->CallOperator;
3522 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3523 currentDecl = CSI->TheCapturedDecl;
3524 else
3525 currentDecl = getCurFunctionOrMethodDecl();
3527 if (!currentDecl) {
3528 Diag(Loc, diag::ext_predef_outside_function);
3529 currentDecl = Context.getTranslationUnitDecl();
3532 QualType ResTy;
3533 StringLiteral *SL = nullptr;
3534 if (cast<DeclContext>(currentDecl)->isDependentContext())
3535 ResTy = Context.DependentTy;
3536 else {
3537 // Pre-defined identifiers are of type char[x], where x is the length of
3538 // the string.
3539 auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3540 unsigned Length = Str.length();
3542 llvm::APInt LengthI(32, Length + 1);
3543 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3544 ResTy =
3545 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3546 SmallString<32> RawChars;
3547 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3548 Str, RawChars);
3549 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3550 ArrayType::Normal,
3551 /*IndexTypeQuals*/ 0);
3552 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3553 /*Pascal*/ false, ResTy, Loc);
3554 } else {
3555 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3556 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3557 ArrayType::Normal,
3558 /*IndexTypeQuals*/ 0);
3559 SL = StringLiteral::Create(Context, Str, StringLiteral::Ordinary,
3560 /*Pascal*/ false, ResTy, Loc);
3564 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3567 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3568 SourceLocation LParen,
3569 SourceLocation RParen,
3570 TypeSourceInfo *TSI) {
3571 return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3574 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3575 SourceLocation LParen,
3576 SourceLocation RParen,
3577 ParsedType ParsedTy) {
3578 TypeSourceInfo *TSI = nullptr;
3579 QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3581 if (Ty.isNull())
3582 return ExprError();
3583 if (!TSI)
3584 TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3586 return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3589 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3590 PredefinedExpr::IdentKind IK;
3592 switch (Kind) {
3593 default: llvm_unreachable("Unknown simple primary expr!");
3594 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3595 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3596 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3597 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3598 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3599 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3600 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3603 return BuildPredefinedExpr(Loc, IK);
3606 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3607 SmallString<16> CharBuffer;
3608 bool Invalid = false;
3609 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3610 if (Invalid)
3611 return ExprError();
3613 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3614 PP, Tok.getKind());
3615 if (Literal.hadError())
3616 return ExprError();
3618 QualType Ty;
3619 if (Literal.isWide())
3620 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3621 else if (Literal.isUTF8() && getLangOpts().C2x)
3622 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C2x
3623 else if (Literal.isUTF8() && getLangOpts().Char8)
3624 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3625 else if (Literal.isUTF16())
3626 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3627 else if (Literal.isUTF32())
3628 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3629 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3630 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3631 else
3632 Ty = Context.CharTy; // 'x' -> char in C++;
3633 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3635 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3636 if (Literal.isWide())
3637 Kind = CharacterLiteral::Wide;
3638 else if (Literal.isUTF16())
3639 Kind = CharacterLiteral::UTF16;
3640 else if (Literal.isUTF32())
3641 Kind = CharacterLiteral::UTF32;
3642 else if (Literal.isUTF8())
3643 Kind = CharacterLiteral::UTF8;
3645 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3646 Tok.getLocation());
3648 if (Literal.getUDSuffix().empty())
3649 return Lit;
3651 // We're building a user-defined literal.
3652 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3653 SourceLocation UDSuffixLoc =
3654 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3656 // Make sure we're allowed user-defined literals here.
3657 if (!UDLScope)
3658 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3660 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3661 // operator "" X (ch)
3662 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3663 Lit, Tok.getLocation());
3666 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3667 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3668 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3669 Context.IntTy, Loc);
3672 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3673 QualType Ty, SourceLocation Loc) {
3674 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3676 using llvm::APFloat;
3677 APFloat Val(Format);
3679 APFloat::opStatus result = Literal.GetFloatValue(Val);
3681 // Overflow is always an error, but underflow is only an error if
3682 // we underflowed to zero (APFloat reports denormals as underflow).
3683 if ((result & APFloat::opOverflow) ||
3684 ((result & APFloat::opUnderflow) && Val.isZero())) {
3685 unsigned diagnostic;
3686 SmallString<20> buffer;
3687 if (result & APFloat::opOverflow) {
3688 diagnostic = diag::warn_float_overflow;
3689 APFloat::getLargest(Format).toString(buffer);
3690 } else {
3691 diagnostic = diag::warn_float_underflow;
3692 APFloat::getSmallest(Format).toString(buffer);
3695 S.Diag(Loc, diagnostic)
3696 << Ty
3697 << StringRef(buffer.data(), buffer.size());
3700 bool isExact = (result == APFloat::opOK);
3701 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3704 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3705 assert(E && "Invalid expression");
3707 if (E->isValueDependent())
3708 return false;
3710 QualType QT = E->getType();
3711 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3712 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3713 return true;
3716 llvm::APSInt ValueAPS;
3717 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3719 if (R.isInvalid())
3720 return true;
3722 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3723 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3724 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3725 << toString(ValueAPS, 10) << ValueIsPositive;
3726 return true;
3729 return false;
3732 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3733 // Fast path for a single digit (which is quite common). A single digit
3734 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3735 if (Tok.getLength() == 1) {
3736 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3737 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3740 SmallString<128> SpellingBuffer;
3741 // NumericLiteralParser wants to overread by one character. Add padding to
3742 // the buffer in case the token is copied to the buffer. If getSpelling()
3743 // returns a StringRef to the memory buffer, it should have a null char at
3744 // the EOF, so it is also safe.
3745 SpellingBuffer.resize(Tok.getLength() + 1);
3747 // Get the spelling of the token, which eliminates trigraphs, etc.
3748 bool Invalid = false;
3749 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3750 if (Invalid)
3751 return ExprError();
3753 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3754 PP.getSourceManager(), PP.getLangOpts(),
3755 PP.getTargetInfo(), PP.getDiagnostics());
3756 if (Literal.hadError)
3757 return ExprError();
3759 if (Literal.hasUDSuffix()) {
3760 // We're building a user-defined literal.
3761 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3762 SourceLocation UDSuffixLoc =
3763 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3765 // Make sure we're allowed user-defined literals here.
3766 if (!UDLScope)
3767 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3769 QualType CookedTy;
3770 if (Literal.isFloatingLiteral()) {
3771 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3772 // long double, the literal is treated as a call of the form
3773 // operator "" X (f L)
3774 CookedTy = Context.LongDoubleTy;
3775 } else {
3776 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3777 // unsigned long long, the literal is treated as a call of the form
3778 // operator "" X (n ULL)
3779 CookedTy = Context.UnsignedLongLongTy;
3782 DeclarationName OpName =
3783 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3784 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3785 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3787 SourceLocation TokLoc = Tok.getLocation();
3789 // Perform literal operator lookup to determine if we're building a raw
3790 // literal or a cooked one.
3791 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3792 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3793 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3794 /*AllowStringTemplatePack*/ false,
3795 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3796 case LOLR_ErrorNoDiagnostic:
3797 // Lookup failure for imaginary constants isn't fatal, there's still the
3798 // GNU extension producing _Complex types.
3799 break;
3800 case LOLR_Error:
3801 return ExprError();
3802 case LOLR_Cooked: {
3803 Expr *Lit;
3804 if (Literal.isFloatingLiteral()) {
3805 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3806 } else {
3807 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3808 if (Literal.GetIntegerValue(ResultVal))
3809 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3810 << /* Unsigned */ 1;
3811 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3812 Tok.getLocation());
3814 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3817 case LOLR_Raw: {
3818 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3819 // literal is treated as a call of the form
3820 // operator "" X ("n")
3821 unsigned Length = Literal.getUDSuffixOffset();
3822 QualType StrTy = Context.getConstantArrayType(
3823 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3824 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3825 Expr *Lit =
3826 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3827 StringLiteral::Ordinary,
3828 /*Pascal*/ false, StrTy, &TokLoc, 1);
3829 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3832 case LOLR_Template: {
3833 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3834 // template), L is treated as a call fo the form
3835 // operator "" X <'c1', 'c2', ... 'ck'>()
3836 // where n is the source character sequence c1 c2 ... ck.
3837 TemplateArgumentListInfo ExplicitArgs;
3838 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3839 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3840 llvm::APSInt Value(CharBits, CharIsUnsigned);
3841 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3842 Value = TokSpelling[I];
3843 TemplateArgument Arg(Context, Value, Context.CharTy);
3844 TemplateArgumentLocInfo ArgInfo;
3845 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3847 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3848 &ExplicitArgs);
3850 case LOLR_StringTemplatePack:
3851 llvm_unreachable("unexpected literal operator lookup result");
3855 Expr *Res;
3857 if (Literal.isFixedPointLiteral()) {
3858 QualType Ty;
3860 if (Literal.isAccum) {
3861 if (Literal.isHalf) {
3862 Ty = Context.ShortAccumTy;
3863 } else if (Literal.isLong) {
3864 Ty = Context.LongAccumTy;
3865 } else {
3866 Ty = Context.AccumTy;
3868 } else if (Literal.isFract) {
3869 if (Literal.isHalf) {
3870 Ty = Context.ShortFractTy;
3871 } else if (Literal.isLong) {
3872 Ty = Context.LongFractTy;
3873 } else {
3874 Ty = Context.FractTy;
3878 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3880 bool isSigned = !Literal.isUnsigned;
3881 unsigned scale = Context.getFixedPointScale(Ty);
3882 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3884 llvm::APInt Val(bit_width, 0, isSigned);
3885 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3886 bool ValIsZero = Val.isZero() && !Overflowed;
3888 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3889 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3890 // Clause 6.4.4 - The value of a constant shall be in the range of
3891 // representable values for its type, with exception for constants of a
3892 // fract type with a value of exactly 1; such a constant shall denote
3893 // the maximal value for the type.
3894 --Val;
3895 else if (Val.ugt(MaxVal) || Overflowed)
3896 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3898 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3899 Tok.getLocation(), scale);
3900 } else if (Literal.isFloatingLiteral()) {
3901 QualType Ty;
3902 if (Literal.isHalf){
3903 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3904 Ty = Context.HalfTy;
3905 else {
3906 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3907 return ExprError();
3909 } else if (Literal.isFloat)
3910 Ty = Context.FloatTy;
3911 else if (Literal.isLong)
3912 Ty = Context.LongDoubleTy;
3913 else if (Literal.isFloat16)
3914 Ty = Context.Float16Ty;
3915 else if (Literal.isFloat128)
3916 Ty = Context.Float128Ty;
3917 else
3918 Ty = Context.DoubleTy;
3920 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3922 if (Ty == Context.DoubleTy) {
3923 if (getLangOpts().SinglePrecisionConstants) {
3924 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3925 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3927 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3928 "cl_khr_fp64", getLangOpts())) {
3929 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3930 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3931 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3932 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3935 } else if (!Literal.isIntegerLiteral()) {
3936 return ExprError();
3937 } else {
3938 QualType Ty;
3940 // 'z/uz' literals are a C++2b feature.
3941 if (Literal.isSizeT)
3942 Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3943 ? getLangOpts().CPlusPlus2b
3944 ? diag::warn_cxx20_compat_size_t_suffix
3945 : diag::ext_cxx2b_size_t_suffix
3946 : diag::err_cxx2b_size_t_suffix);
3948 // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++,
3949 // but we do not currently support the suffix in C++ mode because it's not
3950 // entirely clear whether WG21 will prefer this suffix to return a library
3951 // type such as std::bit_int instead of returning a _BitInt.
3952 if (Literal.isBitInt && !getLangOpts().CPlusPlus)
3953 PP.Diag(Tok.getLocation(), getLangOpts().C2x
3954 ? diag::warn_c2x_compat_bitint_suffix
3955 : diag::ext_c2x_bitint_suffix);
3957 // Get the value in the widest-possible width. What is "widest" depends on
3958 // whether the literal is a bit-precise integer or not. For a bit-precise
3959 // integer type, try to scan the source to determine how many bits are
3960 // needed to represent the value. This may seem a bit expensive, but trying
3961 // to get the integer value from an overly-wide APInt is *extremely*
3962 // expensive, so the naive approach of assuming
3963 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3964 unsigned BitsNeeded =
3965 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
3966 Literal.getLiteralDigits(), Literal.getRadix())
3967 : Context.getTargetInfo().getIntMaxTWidth();
3968 llvm::APInt ResultVal(BitsNeeded, 0);
3970 if (Literal.GetIntegerValue(ResultVal)) {
3971 // If this value didn't fit into uintmax_t, error and force to ull.
3972 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3973 << /* Unsigned */ 1;
3974 Ty = Context.UnsignedLongLongTy;
3975 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3976 "long long is not intmax_t?");
3977 } else {
3978 // If this value fits into a ULL, try to figure out what else it fits into
3979 // according to the rules of C99 6.4.4.1p5.
3981 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3982 // be an unsigned int.
3983 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3985 // Check from smallest to largest, picking the smallest type we can.
3986 unsigned Width = 0;
3988 // Microsoft specific integer suffixes are explicitly sized.
3989 if (Literal.MicrosoftInteger) {
3990 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3991 Width = 8;
3992 Ty = Context.CharTy;
3993 } else {
3994 Width = Literal.MicrosoftInteger;
3995 Ty = Context.getIntTypeForBitwidth(Width,
3996 /*Signed=*/!Literal.isUnsigned);
4000 // Bit-precise integer literals are automagically-sized based on the
4001 // width required by the literal.
4002 if (Literal.isBitInt) {
4003 // The signed version has one more bit for the sign value. There are no
4004 // zero-width bit-precise integers, even if the literal value is 0.
4005 Width = std::max(ResultVal.getActiveBits(), 1u) +
4006 (Literal.isUnsigned ? 0u : 1u);
4008 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4009 // and reset the type to the largest supported width.
4010 unsigned int MaxBitIntWidth =
4011 Context.getTargetInfo().getMaxBitIntWidth();
4012 if (Width > MaxBitIntWidth) {
4013 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4014 << Literal.isUnsigned;
4015 Width = MaxBitIntWidth;
4018 // Reset the result value to the smaller APInt and select the correct
4019 // type to be used. Note, we zext even for signed values because the
4020 // literal itself is always an unsigned value (a preceeding - is a
4021 // unary operator, not part of the literal).
4022 ResultVal = ResultVal.zextOrTrunc(Width);
4023 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4026 // Check C++2b size_t literals.
4027 if (Literal.isSizeT) {
4028 assert(!Literal.MicrosoftInteger &&
4029 "size_t literals can't be Microsoft literals");
4030 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4031 Context.getTargetInfo().getSizeType());
4033 // Does it fit in size_t?
4034 if (ResultVal.isIntN(SizeTSize)) {
4035 // Does it fit in ssize_t?
4036 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4037 Ty = Context.getSignedSizeType();
4038 else if (AllowUnsigned)
4039 Ty = Context.getSizeType();
4040 Width = SizeTSize;
4044 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4045 !Literal.isSizeT) {
4046 // Are int/unsigned possibilities?
4047 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4049 // Does it fit in a unsigned int?
4050 if (ResultVal.isIntN(IntSize)) {
4051 // Does it fit in a signed int?
4052 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4053 Ty = Context.IntTy;
4054 else if (AllowUnsigned)
4055 Ty = Context.UnsignedIntTy;
4056 Width = IntSize;
4060 // Are long/unsigned long possibilities?
4061 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4062 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4064 // Does it fit in a unsigned long?
4065 if (ResultVal.isIntN(LongSize)) {
4066 // Does it fit in a signed long?
4067 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4068 Ty = Context.LongTy;
4069 else if (AllowUnsigned)
4070 Ty = Context.UnsignedLongTy;
4071 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4072 // is compatible.
4073 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4074 const unsigned LongLongSize =
4075 Context.getTargetInfo().getLongLongWidth();
4076 Diag(Tok.getLocation(),
4077 getLangOpts().CPlusPlus
4078 ? Literal.isLong
4079 ? diag::warn_old_implicitly_unsigned_long_cxx
4080 : /*C++98 UB*/ diag::
4081 ext_old_implicitly_unsigned_long_cxx
4082 : diag::warn_old_implicitly_unsigned_long)
4083 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4084 : /*will be ill-formed*/ 1);
4085 Ty = Context.UnsignedLongTy;
4087 Width = LongSize;
4091 // Check long long if needed.
4092 if (Ty.isNull() && !Literal.isSizeT) {
4093 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4095 // Does it fit in a unsigned long long?
4096 if (ResultVal.isIntN(LongLongSize)) {
4097 // Does it fit in a signed long long?
4098 // To be compatible with MSVC, hex integer literals ending with the
4099 // LL or i64 suffix are always signed in Microsoft mode.
4100 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4101 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4102 Ty = Context.LongLongTy;
4103 else if (AllowUnsigned)
4104 Ty = Context.UnsignedLongLongTy;
4105 Width = LongLongSize;
4107 // 'long long' is a C99 or C++11 feature, whether the literal
4108 // explicitly specified 'long long' or we needed the extra width.
4109 if (getLangOpts().CPlusPlus)
4110 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4111 ? diag::warn_cxx98_compat_longlong
4112 : diag::ext_cxx11_longlong);
4113 else if (!getLangOpts().C99)
4114 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4118 // If we still couldn't decide a type, we either have 'size_t' literal
4119 // that is out of range, or a decimal literal that does not fit in a
4120 // signed long long and has no U suffix.
4121 if (Ty.isNull()) {
4122 if (Literal.isSizeT)
4123 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4124 << Literal.isUnsigned;
4125 else
4126 Diag(Tok.getLocation(),
4127 diag::ext_integer_literal_too_large_for_signed);
4128 Ty = Context.UnsignedLongLongTy;
4129 Width = Context.getTargetInfo().getLongLongWidth();
4132 if (ResultVal.getBitWidth() != Width)
4133 ResultVal = ResultVal.trunc(Width);
4135 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4138 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4139 if (Literal.isImaginary) {
4140 Res = new (Context) ImaginaryLiteral(Res,
4141 Context.getComplexType(Res->getType()));
4143 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4145 return Res;
4148 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4149 assert(E && "ActOnParenExpr() missing expr");
4150 QualType ExprTy = E->getType();
4151 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4152 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4153 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4154 return new (Context) ParenExpr(L, R, E);
4157 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4158 SourceLocation Loc,
4159 SourceRange ArgRange) {
4160 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4161 // scalar or vector data type argument..."
4162 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4163 // type (C99 6.2.5p18) or void.
4164 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4165 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4166 << T << ArgRange;
4167 return true;
4170 assert((T->isVoidType() || !T->isIncompleteType()) &&
4171 "Scalar types should always be complete");
4172 return false;
4175 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4176 SourceLocation Loc,
4177 SourceRange ArgRange,
4178 UnaryExprOrTypeTrait TraitKind) {
4179 // Invalid types must be hard errors for SFINAE in C++.
4180 if (S.LangOpts.CPlusPlus)
4181 return true;
4183 // C99 6.5.3.4p1:
4184 if (T->isFunctionType() &&
4185 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4186 TraitKind == UETT_PreferredAlignOf)) {
4187 // sizeof(function)/alignof(function) is allowed as an extension.
4188 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4189 << getTraitSpelling(TraitKind) << ArgRange;
4190 return false;
4193 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4194 // this is an error (OpenCL v1.1 s6.3.k)
4195 if (T->isVoidType()) {
4196 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4197 : diag::ext_sizeof_alignof_void_type;
4198 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4199 return false;
4202 return true;
4205 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4206 SourceLocation Loc,
4207 SourceRange ArgRange,
4208 UnaryExprOrTypeTrait TraitKind) {
4209 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4210 // runtime doesn't allow it.
4211 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4212 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4213 << T << (TraitKind == UETT_SizeOf)
4214 << ArgRange;
4215 return true;
4218 return false;
4221 /// Check whether E is a pointer from a decayed array type (the decayed
4222 /// pointer type is equal to T) and emit a warning if it is.
4223 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4224 Expr *E) {
4225 // Don't warn if the operation changed the type.
4226 if (T != E->getType())
4227 return;
4229 // Now look for array decays.
4230 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4231 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4232 return;
4234 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4235 << ICE->getType()
4236 << ICE->getSubExpr()->getType();
4239 /// Check the constraints on expression operands to unary type expression
4240 /// and type traits.
4242 /// Completes any types necessary and validates the constraints on the operand
4243 /// expression. The logic mostly mirrors the type-based overload, but may modify
4244 /// the expression as it completes the type for that expression through template
4245 /// instantiation, etc.
4246 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4247 UnaryExprOrTypeTrait ExprKind) {
4248 QualType ExprTy = E->getType();
4249 assert(!ExprTy->isReferenceType());
4251 bool IsUnevaluatedOperand =
4252 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4253 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4254 if (IsUnevaluatedOperand) {
4255 ExprResult Result = CheckUnevaluatedOperand(E);
4256 if (Result.isInvalid())
4257 return true;
4258 E = Result.get();
4261 // The operand for sizeof and alignof is in an unevaluated expression context,
4262 // so side effects could result in unintended consequences.
4263 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4264 // used to build SFINAE gadgets.
4265 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4266 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4267 !E->isInstantiationDependent() &&
4268 !E->getType()->isVariableArrayType() &&
4269 E->HasSideEffects(Context, false))
4270 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4272 if (ExprKind == UETT_VecStep)
4273 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4274 E->getSourceRange());
4276 // Explicitly list some types as extensions.
4277 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4278 E->getSourceRange(), ExprKind))
4279 return false;
4281 // 'alignof' applied to an expression only requires the base element type of
4282 // the expression to be complete. 'sizeof' requires the expression's type to
4283 // be complete (and will attempt to complete it if it's an array of unknown
4284 // bound).
4285 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4286 if (RequireCompleteSizedType(
4287 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4288 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4289 getTraitSpelling(ExprKind), E->getSourceRange()))
4290 return true;
4291 } else {
4292 if (RequireCompleteSizedExprType(
4293 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4294 getTraitSpelling(ExprKind), E->getSourceRange()))
4295 return true;
4298 // Completing the expression's type may have changed it.
4299 ExprTy = E->getType();
4300 assert(!ExprTy->isReferenceType());
4302 if (ExprTy->isFunctionType()) {
4303 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4304 << getTraitSpelling(ExprKind) << E->getSourceRange();
4305 return true;
4308 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4309 E->getSourceRange(), ExprKind))
4310 return true;
4312 if (ExprKind == UETT_SizeOf) {
4313 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4314 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4315 QualType OType = PVD->getOriginalType();
4316 QualType Type = PVD->getType();
4317 if (Type->isPointerType() && OType->isArrayType()) {
4318 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4319 << Type << OType;
4320 Diag(PVD->getLocation(), diag::note_declared_at);
4325 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4326 // decays into a pointer and returns an unintended result. This is most
4327 // likely a typo for "sizeof(array) op x".
4328 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4329 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4330 BO->getLHS());
4331 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4332 BO->getRHS());
4336 return false;
4339 /// Check the constraints on operands to unary expression and type
4340 /// traits.
4342 /// This will complete any types necessary, and validate the various constraints
4343 /// on those operands.
4345 /// The UsualUnaryConversions() function is *not* called by this routine.
4346 /// C99 6.3.2.1p[2-4] all state:
4347 /// Except when it is the operand of the sizeof operator ...
4349 /// C++ [expr.sizeof]p4
4350 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4351 /// standard conversions are not applied to the operand of sizeof.
4353 /// This policy is followed for all of the unary trait expressions.
4354 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4355 SourceLocation OpLoc,
4356 SourceRange ExprRange,
4357 UnaryExprOrTypeTrait ExprKind) {
4358 if (ExprType->isDependentType())
4359 return false;
4361 // C++ [expr.sizeof]p2:
4362 // When applied to a reference or a reference type, the result
4363 // is the size of the referenced type.
4364 // C++11 [expr.alignof]p3:
4365 // When alignof is applied to a reference type, the result
4366 // shall be the alignment of the referenced type.
4367 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4368 ExprType = Ref->getPointeeType();
4370 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4371 // When alignof or _Alignof is applied to an array type, the result
4372 // is the alignment of the element type.
4373 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4374 ExprKind == UETT_OpenMPRequiredSimdAlign)
4375 ExprType = Context.getBaseElementType(ExprType);
4377 if (ExprKind == UETT_VecStep)
4378 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4380 // Explicitly list some types as extensions.
4381 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4382 ExprKind))
4383 return false;
4385 if (RequireCompleteSizedType(
4386 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4387 getTraitSpelling(ExprKind), ExprRange))
4388 return true;
4390 if (ExprType->isFunctionType()) {
4391 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4392 << getTraitSpelling(ExprKind) << ExprRange;
4393 return true;
4396 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4397 ExprKind))
4398 return true;
4400 return false;
4403 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4404 // Cannot know anything else if the expression is dependent.
4405 if (E->isTypeDependent())
4406 return false;
4408 if (E->getObjectKind() == OK_BitField) {
4409 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4410 << 1 << E->getSourceRange();
4411 return true;
4414 ValueDecl *D = nullptr;
4415 Expr *Inner = E->IgnoreParens();
4416 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4417 D = DRE->getDecl();
4418 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4419 D = ME->getMemberDecl();
4422 // If it's a field, require the containing struct to have a
4423 // complete definition so that we can compute the layout.
4425 // This can happen in C++11 onwards, either by naming the member
4426 // in a way that is not transformed into a member access expression
4427 // (in an unevaluated operand, for instance), or by naming the member
4428 // in a trailing-return-type.
4430 // For the record, since __alignof__ on expressions is a GCC
4431 // extension, GCC seems to permit this but always gives the
4432 // nonsensical answer 0.
4434 // We don't really need the layout here --- we could instead just
4435 // directly check for all the appropriate alignment-lowing
4436 // attributes --- but that would require duplicating a lot of
4437 // logic that just isn't worth duplicating for such a marginal
4438 // use-case.
4439 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4440 // Fast path this check, since we at least know the record has a
4441 // definition if we can find a member of it.
4442 if (!FD->getParent()->isCompleteDefinition()) {
4443 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4444 << E->getSourceRange();
4445 return true;
4448 // Otherwise, if it's a field, and the field doesn't have
4449 // reference type, then it must have a complete type (or be a
4450 // flexible array member, which we explicitly want to
4451 // white-list anyway), which makes the following checks trivial.
4452 if (!FD->getType()->isReferenceType())
4453 return false;
4456 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4459 bool Sema::CheckVecStepExpr(Expr *E) {
4460 E = E->IgnoreParens();
4462 // Cannot know anything else if the expression is dependent.
4463 if (E->isTypeDependent())
4464 return false;
4466 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4469 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4470 CapturingScopeInfo *CSI) {
4471 assert(T->isVariablyModifiedType());
4472 assert(CSI != nullptr);
4474 // We're going to walk down into the type and look for VLA expressions.
4475 do {
4476 const Type *Ty = T.getTypePtr();
4477 switch (Ty->getTypeClass()) {
4478 #define TYPE(Class, Base)
4479 #define ABSTRACT_TYPE(Class, Base)
4480 #define NON_CANONICAL_TYPE(Class, Base)
4481 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4482 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4483 #include "clang/AST/TypeNodes.inc"
4484 T = QualType();
4485 break;
4486 // These types are never variably-modified.
4487 case Type::Builtin:
4488 case Type::Complex:
4489 case Type::Vector:
4490 case Type::ExtVector:
4491 case Type::ConstantMatrix:
4492 case Type::Record:
4493 case Type::Enum:
4494 case Type::TemplateSpecialization:
4495 case Type::ObjCObject:
4496 case Type::ObjCInterface:
4497 case Type::ObjCObjectPointer:
4498 case Type::ObjCTypeParam:
4499 case Type::Pipe:
4500 case Type::BitInt:
4501 llvm_unreachable("type class is never variably-modified!");
4502 case Type::Elaborated:
4503 T = cast<ElaboratedType>(Ty)->getNamedType();
4504 break;
4505 case Type::Adjusted:
4506 T = cast<AdjustedType>(Ty)->getOriginalType();
4507 break;
4508 case Type::Decayed:
4509 T = cast<DecayedType>(Ty)->getPointeeType();
4510 break;
4511 case Type::Pointer:
4512 T = cast<PointerType>(Ty)->getPointeeType();
4513 break;
4514 case Type::BlockPointer:
4515 T = cast<BlockPointerType>(Ty)->getPointeeType();
4516 break;
4517 case Type::LValueReference:
4518 case Type::RValueReference:
4519 T = cast<ReferenceType>(Ty)->getPointeeType();
4520 break;
4521 case Type::MemberPointer:
4522 T = cast<MemberPointerType>(Ty)->getPointeeType();
4523 break;
4524 case Type::ConstantArray:
4525 case Type::IncompleteArray:
4526 // Losing element qualification here is fine.
4527 T = cast<ArrayType>(Ty)->getElementType();
4528 break;
4529 case Type::VariableArray: {
4530 // Losing element qualification here is fine.
4531 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4533 // Unknown size indication requires no size computation.
4534 // Otherwise, evaluate and record it.
4535 auto Size = VAT->getSizeExpr();
4536 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4537 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4538 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4540 T = VAT->getElementType();
4541 break;
4543 case Type::FunctionProto:
4544 case Type::FunctionNoProto:
4545 T = cast<FunctionType>(Ty)->getReturnType();
4546 break;
4547 case Type::Paren:
4548 case Type::TypeOf:
4549 case Type::UnaryTransform:
4550 case Type::Attributed:
4551 case Type::BTFTagAttributed:
4552 case Type::SubstTemplateTypeParm:
4553 case Type::MacroQualified:
4554 // Keep walking after single level desugaring.
4555 T = T.getSingleStepDesugaredType(Context);
4556 break;
4557 case Type::Typedef:
4558 T = cast<TypedefType>(Ty)->desugar();
4559 break;
4560 case Type::Decltype:
4561 T = cast<DecltypeType>(Ty)->desugar();
4562 break;
4563 case Type::Using:
4564 T = cast<UsingType>(Ty)->desugar();
4565 break;
4566 case Type::Auto:
4567 case Type::DeducedTemplateSpecialization:
4568 T = cast<DeducedType>(Ty)->getDeducedType();
4569 break;
4570 case Type::TypeOfExpr:
4571 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4572 break;
4573 case Type::Atomic:
4574 T = cast<AtomicType>(Ty)->getValueType();
4575 break;
4577 } while (!T.isNull() && T->isVariablyModifiedType());
4580 /// Build a sizeof or alignof expression given a type operand.
4581 ExprResult
4582 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4583 SourceLocation OpLoc,
4584 UnaryExprOrTypeTrait ExprKind,
4585 SourceRange R) {
4586 if (!TInfo)
4587 return ExprError();
4589 QualType T = TInfo->getType();
4591 if (!T->isDependentType() &&
4592 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4593 return ExprError();
4595 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4596 if (auto *TT = T->getAs<TypedefType>()) {
4597 for (auto I = FunctionScopes.rbegin(),
4598 E = std::prev(FunctionScopes.rend());
4599 I != E; ++I) {
4600 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4601 if (CSI == nullptr)
4602 break;
4603 DeclContext *DC = nullptr;
4604 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4605 DC = LSI->CallOperator;
4606 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4607 DC = CRSI->TheCapturedDecl;
4608 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4609 DC = BSI->TheDecl;
4610 if (DC) {
4611 if (DC->containsDecl(TT->getDecl()))
4612 break;
4613 captureVariablyModifiedType(Context, T, CSI);
4619 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4620 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4621 TInfo->getType()->isVariablyModifiedType())
4622 TInfo = TransformToPotentiallyEvaluated(TInfo);
4624 return new (Context) UnaryExprOrTypeTraitExpr(
4625 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4628 /// Build a sizeof or alignof expression given an expression
4629 /// operand.
4630 ExprResult
4631 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4632 UnaryExprOrTypeTrait ExprKind) {
4633 ExprResult PE = CheckPlaceholderExpr(E);
4634 if (PE.isInvalid())
4635 return ExprError();
4637 E = PE.get();
4639 // Verify that the operand is valid.
4640 bool isInvalid = false;
4641 if (E->isTypeDependent()) {
4642 // Delay type-checking for type-dependent expressions.
4643 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4644 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4645 } else if (ExprKind == UETT_VecStep) {
4646 isInvalid = CheckVecStepExpr(E);
4647 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4648 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4649 isInvalid = true;
4650 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4651 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4652 isInvalid = true;
4653 } else {
4654 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4657 if (isInvalid)
4658 return ExprError();
4660 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4661 PE = TransformToPotentiallyEvaluated(E);
4662 if (PE.isInvalid()) return ExprError();
4663 E = PE.get();
4666 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4667 return new (Context) UnaryExprOrTypeTraitExpr(
4668 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4671 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4672 /// expr and the same for @c alignof and @c __alignof
4673 /// Note that the ArgRange is invalid if isType is false.
4674 ExprResult
4675 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4676 UnaryExprOrTypeTrait ExprKind, bool IsType,
4677 void *TyOrEx, SourceRange ArgRange) {
4678 // If error parsing type, ignore.
4679 if (!TyOrEx) return ExprError();
4681 if (IsType) {
4682 TypeSourceInfo *TInfo;
4683 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4684 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4687 Expr *ArgEx = (Expr *)TyOrEx;
4688 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4689 return Result;
4692 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4693 bool IsReal) {
4694 if (V.get()->isTypeDependent())
4695 return S.Context.DependentTy;
4697 // _Real and _Imag are only l-values for normal l-values.
4698 if (V.get()->getObjectKind() != OK_Ordinary) {
4699 V = S.DefaultLvalueConversion(V.get());
4700 if (V.isInvalid())
4701 return QualType();
4704 // These operators return the element type of a complex type.
4705 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4706 return CT->getElementType();
4708 // Otherwise they pass through real integer and floating point types here.
4709 if (V.get()->getType()->isArithmeticType())
4710 return V.get()->getType();
4712 // Test for placeholders.
4713 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4714 if (PR.isInvalid()) return QualType();
4715 if (PR.get() != V.get()) {
4716 V = PR;
4717 return CheckRealImagOperand(S, V, Loc, IsReal);
4720 // Reject anything else.
4721 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4722 << (IsReal ? "__real" : "__imag");
4723 return QualType();
4728 ExprResult
4729 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4730 tok::TokenKind Kind, Expr *Input) {
4731 UnaryOperatorKind Opc;
4732 switch (Kind) {
4733 default: llvm_unreachable("Unknown unary op!");
4734 case tok::plusplus: Opc = UO_PostInc; break;
4735 case tok::minusminus: Opc = UO_PostDec; break;
4738 // Since this might is a postfix expression, get rid of ParenListExprs.
4739 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4740 if (Result.isInvalid()) return ExprError();
4741 Input = Result.get();
4743 return BuildUnaryOp(S, OpLoc, Opc, Input);
4746 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4748 /// \return true on error
4749 static bool checkArithmeticOnObjCPointer(Sema &S,
4750 SourceLocation opLoc,
4751 Expr *op) {
4752 assert(op->getType()->isObjCObjectPointerType());
4753 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4754 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4755 return false;
4757 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4758 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4759 << op->getSourceRange();
4760 return true;
4763 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4764 auto *BaseNoParens = Base->IgnoreParens();
4765 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4766 return MSProp->getPropertyDecl()->getType()->isArrayType();
4767 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4770 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4771 // Typically this is DependentTy, but can sometimes be more precise.
4773 // There are cases when we could determine a non-dependent type:
4774 // - LHS and RHS may have non-dependent types despite being type-dependent
4775 // (e.g. unbounded array static members of the current instantiation)
4776 // - one may be a dependent-sized array with known element type
4777 // - one may be a dependent-typed valid index (enum in current instantiation)
4779 // We *always* return a dependent type, in such cases it is DependentTy.
4780 // This avoids creating type-dependent expressions with non-dependent types.
4781 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4782 static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
4783 const ASTContext &Ctx) {
4784 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4785 QualType LTy = LHS->getType(), RTy = RHS->getType();
4786 QualType Result = Ctx.DependentTy;
4787 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4788 if (const PointerType *PT = LTy->getAs<PointerType>())
4789 Result = PT->getPointeeType();
4790 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4791 Result = AT->getElementType();
4792 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4793 if (const PointerType *PT = RTy->getAs<PointerType>())
4794 Result = PT->getPointeeType();
4795 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4796 Result = AT->getElementType();
4798 // Ensure we return a dependent type.
4799 return Result->isDependentType() ? Result : Ctx.DependentTy;
4802 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args);
4804 ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
4805 SourceLocation lbLoc,
4806 MultiExprArg ArgExprs,
4807 SourceLocation rbLoc) {
4809 if (base && !base->getType().isNull() &&
4810 base->hasPlaceholderType(BuiltinType::OMPArraySection))
4811 return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(),
4812 SourceLocation(), /*Length*/ nullptr,
4813 /*Stride=*/nullptr, rbLoc);
4815 // Since this might be a postfix expression, get rid of ParenListExprs.
4816 if (isa<ParenListExpr>(base)) {
4817 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4818 if (result.isInvalid())
4819 return ExprError();
4820 base = result.get();
4823 // Check if base and idx form a MatrixSubscriptExpr.
4825 // Helper to check for comma expressions, which are not allowed as indices for
4826 // matrix subscript expressions.
4827 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4828 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4829 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4830 << SourceRange(base->getBeginLoc(), rbLoc);
4831 return true;
4833 return false;
4835 // The matrix subscript operator ([][])is considered a single operator.
4836 // Separating the index expressions by parenthesis is not allowed.
4837 if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4838 !isa<MatrixSubscriptExpr>(base)) {
4839 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4840 << SourceRange(base->getBeginLoc(), rbLoc);
4841 return ExprError();
4843 // If the base is a MatrixSubscriptExpr, try to create a new
4844 // MatrixSubscriptExpr.
4845 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4846 if (matSubscriptE) {
4847 assert(ArgExprs.size() == 1);
4848 if (CheckAndReportCommaError(ArgExprs.front()))
4849 return ExprError();
4851 assert(matSubscriptE->isIncomplete() &&
4852 "base has to be an incomplete matrix subscript");
4853 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4854 matSubscriptE->getRowIdx(),
4855 ArgExprs.front(), rbLoc);
4858 // Handle any non-overload placeholder types in the base and index
4859 // expressions. We can't handle overloads here because the other
4860 // operand might be an overloadable type, in which case the overload
4861 // resolution for the operator overload should get the first crack
4862 // at the overload.
4863 bool IsMSPropertySubscript = false;
4864 if (base->getType()->isNonOverloadPlaceholderType()) {
4865 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4866 if (!IsMSPropertySubscript) {
4867 ExprResult result = CheckPlaceholderExpr(base);
4868 if (result.isInvalid())
4869 return ExprError();
4870 base = result.get();
4874 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4875 if (base->getType()->isMatrixType()) {
4876 assert(ArgExprs.size() == 1);
4877 if (CheckAndReportCommaError(ArgExprs.front()))
4878 return ExprError();
4880 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
4881 rbLoc);
4884 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
4885 Expr *idx = ArgExprs[0];
4886 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4887 (isa<CXXOperatorCallExpr>(idx) &&
4888 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
4889 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4890 << SourceRange(base->getBeginLoc(), rbLoc);
4894 if (ArgExprs.size() == 1 &&
4895 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
4896 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
4897 if (result.isInvalid())
4898 return ExprError();
4899 ArgExprs[0] = result.get();
4900 } else {
4901 if (checkArgsForPlaceholders(*this, ArgExprs))
4902 return ExprError();
4905 // Build an unanalyzed expression if either operand is type-dependent.
4906 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
4907 (base->isTypeDependent() ||
4908 Expr::hasAnyTypeDependentArguments(ArgExprs))) {
4909 return new (Context) ArraySubscriptExpr(
4910 base, ArgExprs.front(),
4911 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
4912 VK_LValue, OK_Ordinary, rbLoc);
4915 // MSDN, property (C++)
4916 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4917 // This attribute can also be used in the declaration of an empty array in a
4918 // class or structure definition. For example:
4919 // __declspec(property(get=GetX, put=PutX)) int x[];
4920 // The above statement indicates that x[] can be used with one or more array
4921 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4922 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4923 if (IsMSPropertySubscript) {
4924 assert(ArgExprs.size() == 1);
4925 // Build MS property subscript expression if base is MS property reference
4926 // or MS property subscript.
4927 return new (Context)
4928 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
4929 VK_LValue, OK_Ordinary, rbLoc);
4932 // Use C++ overloaded-operator rules if either operand has record
4933 // type. The spec says to do this if either type is *overloadable*,
4934 // but enum types can't declare subscript operators or conversion
4935 // operators, so there's nothing interesting for overload resolution
4936 // to do if there aren't any record types involved.
4938 // ObjC pointers have their own subscripting logic that is not tied
4939 // to overload resolution and so should not take this path.
4940 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
4941 ((base->getType()->isRecordType() ||
4942 (ArgExprs.size() != 1 || ArgExprs[0]->getType()->isRecordType())))) {
4943 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
4946 ExprResult Res =
4947 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
4949 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4950 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4952 return Res;
4955 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4956 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4957 InitializationKind Kind =
4958 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4959 InitializationSequence InitSeq(*this, Entity, Kind, E);
4960 return InitSeq.Perform(*this, Entity, Kind, E);
4963 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4964 Expr *ColumnIdx,
4965 SourceLocation RBLoc) {
4966 ExprResult BaseR = CheckPlaceholderExpr(Base);
4967 if (BaseR.isInvalid())
4968 return BaseR;
4969 Base = BaseR.get();
4971 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4972 if (RowR.isInvalid())
4973 return RowR;
4974 RowIdx = RowR.get();
4976 if (!ColumnIdx)
4977 return new (Context) MatrixSubscriptExpr(
4978 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4980 // Build an unanalyzed expression if any of the operands is type-dependent.
4981 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4982 ColumnIdx->isTypeDependent())
4983 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4984 Context.DependentTy, RBLoc);
4986 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4987 if (ColumnR.isInvalid())
4988 return ColumnR;
4989 ColumnIdx = ColumnR.get();
4991 // Check that IndexExpr is an integer expression. If it is a constant
4992 // expression, check that it is less than Dim (= the number of elements in the
4993 // corresponding dimension).
4994 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4995 bool IsColumnIdx) -> Expr * {
4996 if (!IndexExpr->getType()->isIntegerType() &&
4997 !IndexExpr->isTypeDependent()) {
4998 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4999 << IsColumnIdx;
5000 return nullptr;
5003 if (Optional<llvm::APSInt> Idx =
5004 IndexExpr->getIntegerConstantExpr(Context)) {
5005 if ((*Idx < 0 || *Idx >= Dim)) {
5006 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5007 << IsColumnIdx << Dim;
5008 return nullptr;
5012 ExprResult ConvExpr =
5013 tryConvertExprToType(IndexExpr, Context.getSizeType());
5014 assert(!ConvExpr.isInvalid() &&
5015 "should be able to convert any integer type to size type");
5016 return ConvExpr.get();
5019 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5020 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5021 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5022 if (!RowIdx || !ColumnIdx)
5023 return ExprError();
5025 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5026 MTy->getElementType(), RBLoc);
5029 void Sema::CheckAddressOfNoDeref(const Expr *E) {
5030 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5031 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5033 // For expressions like `&(*s).b`, the base is recorded and what should be
5034 // checked.
5035 const MemberExpr *Member = nullptr;
5036 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5037 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5039 LastRecord.PossibleDerefs.erase(StrippedExpr);
5042 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5043 if (isUnevaluatedContext())
5044 return;
5046 QualType ResultTy = E->getType();
5047 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5049 // Bail if the element is an array since it is not memory access.
5050 if (isa<ArrayType>(ResultTy))
5051 return;
5053 if (ResultTy->hasAttr(attr::NoDeref)) {
5054 LastRecord.PossibleDerefs.insert(E);
5055 return;
5058 // Check if the base type is a pointer to a member access of a struct
5059 // marked with noderef.
5060 const Expr *Base = E->getBase();
5061 QualType BaseTy = Base->getType();
5062 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5063 // Not a pointer access
5064 return;
5066 const MemberExpr *Member = nullptr;
5067 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5068 Member->isArrow())
5069 Base = Member->getBase();
5071 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5072 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5073 LastRecord.PossibleDerefs.insert(E);
5077 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5078 Expr *LowerBound,
5079 SourceLocation ColonLocFirst,
5080 SourceLocation ColonLocSecond,
5081 Expr *Length, Expr *Stride,
5082 SourceLocation RBLoc) {
5083 if (Base->hasPlaceholderType() &&
5084 !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5085 ExprResult Result = CheckPlaceholderExpr(Base);
5086 if (Result.isInvalid())
5087 return ExprError();
5088 Base = Result.get();
5090 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
5091 ExprResult Result = CheckPlaceholderExpr(LowerBound);
5092 if (Result.isInvalid())
5093 return ExprError();
5094 Result = DefaultLvalueConversion(Result.get());
5095 if (Result.isInvalid())
5096 return ExprError();
5097 LowerBound = Result.get();
5099 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
5100 ExprResult Result = CheckPlaceholderExpr(Length);
5101 if (Result.isInvalid())
5102 return ExprError();
5103 Result = DefaultLvalueConversion(Result.get());
5104 if (Result.isInvalid())
5105 return ExprError();
5106 Length = Result.get();
5108 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
5109 ExprResult Result = CheckPlaceholderExpr(Stride);
5110 if (Result.isInvalid())
5111 return ExprError();
5112 Result = DefaultLvalueConversion(Result.get());
5113 if (Result.isInvalid())
5114 return ExprError();
5115 Stride = Result.get();
5118 // Build an unanalyzed expression if either operand is type-dependent.
5119 if (Base->isTypeDependent() ||
5120 (LowerBound &&
5121 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
5122 (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
5123 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
5124 return new (Context) OMPArraySectionExpr(
5125 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
5126 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5129 // Perform default conversions.
5130 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
5131 QualType ResultTy;
5132 if (OriginalTy->isAnyPointerType()) {
5133 ResultTy = OriginalTy->getPointeeType();
5134 } else if (OriginalTy->isArrayType()) {
5135 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
5136 } else {
5137 return ExprError(
5138 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
5139 << Base->getSourceRange());
5141 // C99 6.5.2.1p1
5142 if (LowerBound) {
5143 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
5144 LowerBound);
5145 if (Res.isInvalid())
5146 return ExprError(Diag(LowerBound->getExprLoc(),
5147 diag::err_omp_typecheck_section_not_integer)
5148 << 0 << LowerBound->getSourceRange());
5149 LowerBound = Res.get();
5151 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5152 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5153 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
5154 << 0 << LowerBound->getSourceRange();
5156 if (Length) {
5157 auto Res =
5158 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
5159 if (Res.isInvalid())
5160 return ExprError(Diag(Length->getExprLoc(),
5161 diag::err_omp_typecheck_section_not_integer)
5162 << 1 << Length->getSourceRange());
5163 Length = Res.get();
5165 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5166 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5167 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5168 << 1 << Length->getSourceRange();
5170 if (Stride) {
5171 ExprResult Res =
5172 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
5173 if (Res.isInvalid())
5174 return ExprError(Diag(Stride->getExprLoc(),
5175 diag::err_omp_typecheck_section_not_integer)
5176 << 1 << Stride->getSourceRange());
5177 Stride = Res.get();
5179 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5180 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5181 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5182 << 1 << Stride->getSourceRange();
5185 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5186 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5187 // type. Note that functions are not objects, and that (in C99 parlance)
5188 // incomplete types are not object types.
5189 if (ResultTy->isFunctionType()) {
5190 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5191 << ResultTy << Base->getSourceRange();
5192 return ExprError();
5195 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5196 diag::err_omp_section_incomplete_type, Base))
5197 return ExprError();
5199 if (LowerBound && !OriginalTy->isAnyPointerType()) {
5200 Expr::EvalResult Result;
5201 if (LowerBound->EvaluateAsInt(Result, Context)) {
5202 // OpenMP 5.0, [2.1.5 Array Sections]
5203 // The array section must be a subset of the original array.
5204 llvm::APSInt LowerBoundValue = Result.Val.getInt();
5205 if (LowerBoundValue.isNegative()) {
5206 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5207 << LowerBound->getSourceRange();
5208 return ExprError();
5213 if (Length) {
5214 Expr::EvalResult Result;
5215 if (Length->EvaluateAsInt(Result, Context)) {
5216 // OpenMP 5.0, [2.1.5 Array Sections]
5217 // The length must evaluate to non-negative integers.
5218 llvm::APSInt LengthValue = Result.Val.getInt();
5219 if (LengthValue.isNegative()) {
5220 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5221 << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5222 << Length->getSourceRange();
5223 return ExprError();
5226 } else if (ColonLocFirst.isValid() &&
5227 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5228 !OriginalTy->isVariableArrayType()))) {
5229 // OpenMP 5.0, [2.1.5 Array Sections]
5230 // When the size of the array dimension is not known, the length must be
5231 // specified explicitly.
5232 Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5233 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5234 return ExprError();
5237 if (Stride) {
5238 Expr::EvalResult Result;
5239 if (Stride->EvaluateAsInt(Result, Context)) {
5240 // OpenMP 5.0, [2.1.5 Array Sections]
5241 // The stride must evaluate to a positive integer.
5242 llvm::APSInt StrideValue = Result.Val.getInt();
5243 if (!StrideValue.isStrictlyPositive()) {
5244 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5245 << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5246 << Stride->getSourceRange();
5247 return ExprError();
5252 if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5253 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5254 if (Result.isInvalid())
5255 return ExprError();
5256 Base = Result.get();
5258 return new (Context) OMPArraySectionExpr(
5259 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5260 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5263 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5264 SourceLocation RParenLoc,
5265 ArrayRef<Expr *> Dims,
5266 ArrayRef<SourceRange> Brackets) {
5267 if (Base->hasPlaceholderType()) {
5268 ExprResult Result = CheckPlaceholderExpr(Base);
5269 if (Result.isInvalid())
5270 return ExprError();
5271 Result = DefaultLvalueConversion(Result.get());
5272 if (Result.isInvalid())
5273 return ExprError();
5274 Base = Result.get();
5276 QualType BaseTy = Base->getType();
5277 // Delay analysis of the types/expressions if instantiation/specialization is
5278 // required.
5279 if (!BaseTy->isPointerType() && Base->isTypeDependent())
5280 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5281 LParenLoc, RParenLoc, Dims, Brackets);
5282 if (!BaseTy->isPointerType() ||
5283 (!Base->isTypeDependent() &&
5284 BaseTy->getPointeeType()->isIncompleteType()))
5285 return ExprError(Diag(Base->getExprLoc(),
5286 diag::err_omp_non_pointer_type_array_shaping_base)
5287 << Base->getSourceRange());
5289 SmallVector<Expr *, 4> NewDims;
5290 bool ErrorFound = false;
5291 for (Expr *Dim : Dims) {
5292 if (Dim->hasPlaceholderType()) {
5293 ExprResult Result = CheckPlaceholderExpr(Dim);
5294 if (Result.isInvalid()) {
5295 ErrorFound = true;
5296 continue;
5298 Result = DefaultLvalueConversion(Result.get());
5299 if (Result.isInvalid()) {
5300 ErrorFound = true;
5301 continue;
5303 Dim = Result.get();
5305 if (!Dim->isTypeDependent()) {
5306 ExprResult Result =
5307 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5308 if (Result.isInvalid()) {
5309 ErrorFound = true;
5310 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5311 << Dim->getSourceRange();
5312 continue;
5314 Dim = Result.get();
5315 Expr::EvalResult EvResult;
5316 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5317 // OpenMP 5.0, [2.1.4 Array Shaping]
5318 // Each si is an integral type expression that must evaluate to a
5319 // positive integer.
5320 llvm::APSInt Value = EvResult.Val.getInt();
5321 if (!Value.isStrictlyPositive()) {
5322 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5323 << toString(Value, /*Radix=*/10, /*Signed=*/true)
5324 << Dim->getSourceRange();
5325 ErrorFound = true;
5326 continue;
5330 NewDims.push_back(Dim);
5332 if (ErrorFound)
5333 return ExprError();
5334 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5335 LParenLoc, RParenLoc, NewDims, Brackets);
5338 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5339 SourceLocation LLoc, SourceLocation RLoc,
5340 ArrayRef<OMPIteratorData> Data) {
5341 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5342 bool IsCorrect = true;
5343 for (const OMPIteratorData &D : Data) {
5344 TypeSourceInfo *TInfo = nullptr;
5345 SourceLocation StartLoc;
5346 QualType DeclTy;
5347 if (!D.Type.getAsOpaquePtr()) {
5348 // OpenMP 5.0, 2.1.6 Iterators
5349 // In an iterator-specifier, if the iterator-type is not specified then
5350 // the type of that iterator is of int type.
5351 DeclTy = Context.IntTy;
5352 StartLoc = D.DeclIdentLoc;
5353 } else {
5354 DeclTy = GetTypeFromParser(D.Type, &TInfo);
5355 StartLoc = TInfo->getTypeLoc().getBeginLoc();
5358 bool IsDeclTyDependent = DeclTy->isDependentType() ||
5359 DeclTy->containsUnexpandedParameterPack() ||
5360 DeclTy->isInstantiationDependentType();
5361 if (!IsDeclTyDependent) {
5362 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5363 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5364 // The iterator-type must be an integral or pointer type.
5365 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5366 << DeclTy;
5367 IsCorrect = false;
5368 continue;
5370 if (DeclTy.isConstant(Context)) {
5371 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5372 // The iterator-type must not be const qualified.
5373 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5374 << DeclTy;
5375 IsCorrect = false;
5376 continue;
5380 // Iterator declaration.
5381 assert(D.DeclIdent && "Identifier expected.");
5382 // Always try to create iterator declarator to avoid extra error messages
5383 // about unknown declarations use.
5384 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5385 D.DeclIdent, DeclTy, TInfo, SC_None);
5386 VD->setImplicit();
5387 if (S) {
5388 // Check for conflicting previous declaration.
5389 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5390 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5391 ForVisibleRedeclaration);
5392 Previous.suppressDiagnostics();
5393 LookupName(Previous, S);
5395 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5396 /*AllowInlineNamespace=*/false);
5397 if (!Previous.empty()) {
5398 NamedDecl *Old = Previous.getRepresentativeDecl();
5399 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5400 Diag(Old->getLocation(), diag::note_previous_definition);
5401 } else {
5402 PushOnScopeChains(VD, S);
5404 } else {
5405 CurContext->addDecl(VD);
5407 Expr *Begin = D.Range.Begin;
5408 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5409 ExprResult BeginRes =
5410 PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5411 Begin = BeginRes.get();
5413 Expr *End = D.Range.End;
5414 if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5415 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5416 End = EndRes.get();
5418 Expr *Step = D.Range.Step;
5419 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5420 if (!Step->getType()->isIntegralType(Context)) {
5421 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5422 << Step << Step->getSourceRange();
5423 IsCorrect = false;
5424 continue;
5426 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5427 // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5428 // If the step expression of a range-specification equals zero, the
5429 // behavior is unspecified.
5430 if (Result && Result->isZero()) {
5431 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5432 << Step << Step->getSourceRange();
5433 IsCorrect = false;
5434 continue;
5437 if (!Begin || !End || !IsCorrect) {
5438 IsCorrect = false;
5439 continue;
5441 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5442 IDElem.IteratorDecl = VD;
5443 IDElem.AssignmentLoc = D.AssignLoc;
5444 IDElem.Range.Begin = Begin;
5445 IDElem.Range.End = End;
5446 IDElem.Range.Step = Step;
5447 IDElem.ColonLoc = D.ColonLoc;
5448 IDElem.SecondColonLoc = D.SecColonLoc;
5450 if (!IsCorrect) {
5451 // Invalidate all created iterator declarations if error is found.
5452 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5453 if (Decl *ID = D.IteratorDecl)
5454 ID->setInvalidDecl();
5456 return ExprError();
5458 SmallVector<OMPIteratorHelperData, 4> Helpers;
5459 if (!CurContext->isDependentContext()) {
5460 // Build number of ityeration for each iteration range.
5461 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5462 // ((Begini-Stepi-1-Endi) / -Stepi);
5463 for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5464 // (Endi - Begini)
5465 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5466 D.Range.Begin);
5467 if(!Res.isUsable()) {
5468 IsCorrect = false;
5469 continue;
5471 ExprResult St, St1;
5472 if (D.Range.Step) {
5473 St = D.Range.Step;
5474 // (Endi - Begini) + Stepi
5475 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5476 if (!Res.isUsable()) {
5477 IsCorrect = false;
5478 continue;
5480 // (Endi - Begini) + Stepi - 1
5481 Res =
5482 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5483 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5484 if (!Res.isUsable()) {
5485 IsCorrect = false;
5486 continue;
5488 // ((Endi - Begini) + Stepi - 1) / Stepi
5489 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5490 if (!Res.isUsable()) {
5491 IsCorrect = false;
5492 continue;
5494 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5495 // (Begini - Endi)
5496 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5497 D.Range.Begin, D.Range.End);
5498 if (!Res1.isUsable()) {
5499 IsCorrect = false;
5500 continue;
5502 // (Begini - Endi) - Stepi
5503 Res1 =
5504 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5505 if (!Res1.isUsable()) {
5506 IsCorrect = false;
5507 continue;
5509 // (Begini - Endi) - Stepi - 1
5510 Res1 =
5511 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5512 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5513 if (!Res1.isUsable()) {
5514 IsCorrect = false;
5515 continue;
5517 // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5518 Res1 =
5519 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5520 if (!Res1.isUsable()) {
5521 IsCorrect = false;
5522 continue;
5524 // Stepi > 0.
5525 ExprResult CmpRes =
5526 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5527 ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5528 if (!CmpRes.isUsable()) {
5529 IsCorrect = false;
5530 continue;
5532 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5533 Res.get(), Res1.get());
5534 if (!Res.isUsable()) {
5535 IsCorrect = false;
5536 continue;
5539 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5540 if (!Res.isUsable()) {
5541 IsCorrect = false;
5542 continue;
5545 // Build counter update.
5546 // Build counter.
5547 auto *CounterVD =
5548 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5549 D.IteratorDecl->getBeginLoc(), nullptr,
5550 Res.get()->getType(), nullptr, SC_None);
5551 CounterVD->setImplicit();
5552 ExprResult RefRes =
5553 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5554 D.IteratorDecl->getBeginLoc());
5555 // Build counter update.
5556 // I = Begini + counter * Stepi;
5557 ExprResult UpdateRes;
5558 if (D.Range.Step) {
5559 UpdateRes = CreateBuiltinBinOp(
5560 D.AssignmentLoc, BO_Mul,
5561 DefaultLvalueConversion(RefRes.get()).get(), St.get());
5562 } else {
5563 UpdateRes = DefaultLvalueConversion(RefRes.get());
5565 if (!UpdateRes.isUsable()) {
5566 IsCorrect = false;
5567 continue;
5569 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5570 UpdateRes.get());
5571 if (!UpdateRes.isUsable()) {
5572 IsCorrect = false;
5573 continue;
5575 ExprResult VDRes =
5576 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5577 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5578 D.IteratorDecl->getBeginLoc());
5579 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5580 UpdateRes.get());
5581 if (!UpdateRes.isUsable()) {
5582 IsCorrect = false;
5583 continue;
5585 UpdateRes =
5586 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5587 if (!UpdateRes.isUsable()) {
5588 IsCorrect = false;
5589 continue;
5591 ExprResult CounterUpdateRes =
5592 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5593 if (!CounterUpdateRes.isUsable()) {
5594 IsCorrect = false;
5595 continue;
5597 CounterUpdateRes =
5598 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5599 if (!CounterUpdateRes.isUsable()) {
5600 IsCorrect = false;
5601 continue;
5603 OMPIteratorHelperData &HD = Helpers.emplace_back();
5604 HD.CounterVD = CounterVD;
5605 HD.Upper = Res.get();
5606 HD.Update = UpdateRes.get();
5607 HD.CounterUpdate = CounterUpdateRes.get();
5609 } else {
5610 Helpers.assign(ID.size(), {});
5612 if (!IsCorrect) {
5613 // Invalidate all created iterator declarations if error is found.
5614 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5615 if (Decl *ID = D.IteratorDecl)
5616 ID->setInvalidDecl();
5618 return ExprError();
5620 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5621 LLoc, RLoc, ID, Helpers);
5624 ExprResult
5625 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5626 Expr *Idx, SourceLocation RLoc) {
5627 Expr *LHSExp = Base;
5628 Expr *RHSExp = Idx;
5630 ExprValueKind VK = VK_LValue;
5631 ExprObjectKind OK = OK_Ordinary;
5633 // Per C++ core issue 1213, the result is an xvalue if either operand is
5634 // a non-lvalue array, and an lvalue otherwise.
5635 if (getLangOpts().CPlusPlus11) {
5636 for (auto *Op : {LHSExp, RHSExp}) {
5637 Op = Op->IgnoreImplicit();
5638 if (Op->getType()->isArrayType() && !Op->isLValue())
5639 VK = VK_XValue;
5643 // Perform default conversions.
5644 if (!LHSExp->getType()->getAs<VectorType>()) {
5645 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5646 if (Result.isInvalid())
5647 return ExprError();
5648 LHSExp = Result.get();
5650 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5651 if (Result.isInvalid())
5652 return ExprError();
5653 RHSExp = Result.get();
5655 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5657 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5658 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5659 // in the subscript position. As a result, we need to derive the array base
5660 // and index from the expression types.
5661 Expr *BaseExpr, *IndexExpr;
5662 QualType ResultType;
5663 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5664 BaseExpr = LHSExp;
5665 IndexExpr = RHSExp;
5666 ResultType =
5667 getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());
5668 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5669 BaseExpr = LHSExp;
5670 IndexExpr = RHSExp;
5671 ResultType = PTy->getPointeeType();
5672 } else if (const ObjCObjectPointerType *PTy =
5673 LHSTy->getAs<ObjCObjectPointerType>()) {
5674 BaseExpr = LHSExp;
5675 IndexExpr = RHSExp;
5677 // Use custom logic if this should be the pseudo-object subscript
5678 // expression.
5679 if (!LangOpts.isSubscriptPointerArithmetic())
5680 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5681 nullptr);
5683 ResultType = PTy->getPointeeType();
5684 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5685 // Handle the uncommon case of "123[Ptr]".
5686 BaseExpr = RHSExp;
5687 IndexExpr = LHSExp;
5688 ResultType = PTy->getPointeeType();
5689 } else if (const ObjCObjectPointerType *PTy =
5690 RHSTy->getAs<ObjCObjectPointerType>()) {
5691 // Handle the uncommon case of "123[Ptr]".
5692 BaseExpr = RHSExp;
5693 IndexExpr = LHSExp;
5694 ResultType = PTy->getPointeeType();
5695 if (!LangOpts.isSubscriptPointerArithmetic()) {
5696 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5697 << ResultType << BaseExpr->getSourceRange();
5698 return ExprError();
5700 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5701 BaseExpr = LHSExp; // vectors: V[123]
5702 IndexExpr = RHSExp;
5703 // We apply C++ DR1213 to vector subscripting too.
5704 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5705 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5706 if (Materialized.isInvalid())
5707 return ExprError();
5708 LHSExp = Materialized.get();
5710 VK = LHSExp->getValueKind();
5711 if (VK != VK_PRValue)
5712 OK = OK_VectorComponent;
5714 ResultType = VTy->getElementType();
5715 QualType BaseType = BaseExpr->getType();
5716 Qualifiers BaseQuals = BaseType.getQualifiers();
5717 Qualifiers MemberQuals = ResultType.getQualifiers();
5718 Qualifiers Combined = BaseQuals + MemberQuals;
5719 if (Combined != MemberQuals)
5720 ResultType = Context.getQualifiedType(ResultType, Combined);
5721 } else if (LHSTy->isBuiltinType() &&
5722 LHSTy->getAs<BuiltinType>()->isVLSTBuiltinType()) {
5723 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5724 if (BTy->isSVEBool())
5725 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5726 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5728 BaseExpr = LHSExp;
5729 IndexExpr = RHSExp;
5730 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5731 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5732 if (Materialized.isInvalid())
5733 return ExprError();
5734 LHSExp = Materialized.get();
5736 VK = LHSExp->getValueKind();
5737 if (VK != VK_PRValue)
5738 OK = OK_VectorComponent;
5740 ResultType = BTy->getSveEltType(Context);
5742 QualType BaseType = BaseExpr->getType();
5743 Qualifiers BaseQuals = BaseType.getQualifiers();
5744 Qualifiers MemberQuals = ResultType.getQualifiers();
5745 Qualifiers Combined = BaseQuals + MemberQuals;
5746 if (Combined != MemberQuals)
5747 ResultType = Context.getQualifiedType(ResultType, Combined);
5748 } else if (LHSTy->isArrayType()) {
5749 // If we see an array that wasn't promoted by
5750 // DefaultFunctionArrayLvalueConversion, it must be an array that
5751 // wasn't promoted because of the C90 rule that doesn't
5752 // allow promoting non-lvalue arrays. Warn, then
5753 // force the promotion here.
5754 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5755 << LHSExp->getSourceRange();
5756 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5757 CK_ArrayToPointerDecay).get();
5758 LHSTy = LHSExp->getType();
5760 BaseExpr = LHSExp;
5761 IndexExpr = RHSExp;
5762 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5763 } else if (RHSTy->isArrayType()) {
5764 // Same as previous, except for 123[f().a] case
5765 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5766 << RHSExp->getSourceRange();
5767 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5768 CK_ArrayToPointerDecay).get();
5769 RHSTy = RHSExp->getType();
5771 BaseExpr = RHSExp;
5772 IndexExpr = LHSExp;
5773 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5774 } else {
5775 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5776 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5778 // C99 6.5.2.1p1
5779 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5780 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5781 << IndexExpr->getSourceRange());
5783 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5784 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5785 && !IndexExpr->isTypeDependent())
5786 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5788 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5789 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5790 // type. Note that Functions are not objects, and that (in C99 parlance)
5791 // incomplete types are not object types.
5792 if (ResultType->isFunctionType()) {
5793 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5794 << ResultType << BaseExpr->getSourceRange();
5795 return ExprError();
5798 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5799 // GNU extension: subscripting on pointer to void
5800 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5801 << BaseExpr->getSourceRange();
5803 // C forbids expressions of unqualified void type from being l-values.
5804 // See IsCForbiddenLValueType.
5805 if (!ResultType.hasQualifiers())
5806 VK = VK_PRValue;
5807 } else if (!ResultType->isDependentType() &&
5808 RequireCompleteSizedType(
5809 LLoc, ResultType,
5810 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5811 return ExprError();
5813 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5814 !ResultType.isCForbiddenLValueType());
5816 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5817 FunctionScopes.size() > 1) {
5818 if (auto *TT =
5819 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5820 for (auto I = FunctionScopes.rbegin(),
5821 E = std::prev(FunctionScopes.rend());
5822 I != E; ++I) {
5823 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5824 if (CSI == nullptr)
5825 break;
5826 DeclContext *DC = nullptr;
5827 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5828 DC = LSI->CallOperator;
5829 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5830 DC = CRSI->TheCapturedDecl;
5831 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5832 DC = BSI->TheDecl;
5833 if (DC) {
5834 if (DC->containsDecl(TT->getDecl()))
5835 break;
5836 captureVariablyModifiedType(
5837 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5843 return new (Context)
5844 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5847 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5848 ParmVarDecl *Param) {
5849 if (Param->hasUnparsedDefaultArg()) {
5850 // If we've already cleared out the location for the default argument,
5851 // that means we're parsing it right now.
5852 if (!UnparsedDefaultArgLocs.count(Param)) {
5853 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5854 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5855 Param->setInvalidDecl();
5856 return true;
5859 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5860 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5861 Diag(UnparsedDefaultArgLocs[Param],
5862 diag::note_default_argument_declared_here);
5863 return true;
5866 if (Param->hasUninstantiatedDefaultArg() &&
5867 InstantiateDefaultArgument(CallLoc, FD, Param))
5868 return true;
5870 assert(Param->hasInit() && "default argument but no initializer?");
5872 // If the default expression creates temporaries, we need to
5873 // push them to the current stack of expression temporaries so they'll
5874 // be properly destroyed.
5875 // FIXME: We should really be rebuilding the default argument with new
5876 // bound temporaries; see the comment in PR5810.
5877 // We don't need to do that with block decls, though, because
5878 // blocks in default argument expression can never capture anything.
5879 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5880 // Set the "needs cleanups" bit regardless of whether there are
5881 // any explicit objects.
5882 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5884 // Append all the objects to the cleanup list. Right now, this
5885 // should always be a no-op, because blocks in default argument
5886 // expressions should never be able to capture anything.
5887 assert(!Init->getNumObjects() &&
5888 "default argument expression has capturing blocks?");
5891 // We already type-checked the argument, so we know it works.
5892 // Just mark all of the declarations in this potentially-evaluated expression
5893 // as being "referenced".
5894 EnterExpressionEvaluationContext EvalContext(
5895 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5896 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5897 /*SkipLocalVariables=*/true);
5898 return false;
5901 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5902 FunctionDecl *FD, ParmVarDecl *Param) {
5903 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5904 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5905 return ExprError();
5906 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5909 Sema::VariadicCallType
5910 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5911 Expr *Fn) {
5912 if (Proto && Proto->isVariadic()) {
5913 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5914 return VariadicConstructor;
5915 else if (Fn && Fn->getType()->isBlockPointerType())
5916 return VariadicBlock;
5917 else if (FDecl) {
5918 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5919 if (Method->isInstance())
5920 return VariadicMethod;
5921 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5922 return VariadicMethod;
5923 return VariadicFunction;
5925 return VariadicDoesNotApply;
5928 namespace {
5929 class FunctionCallCCC final : public FunctionCallFilterCCC {
5930 public:
5931 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5932 unsigned NumArgs, MemberExpr *ME)
5933 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5934 FunctionName(FuncName) {}
5936 bool ValidateCandidate(const TypoCorrection &candidate) override {
5937 if (!candidate.getCorrectionSpecifier() ||
5938 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5939 return false;
5942 return FunctionCallFilterCCC::ValidateCandidate(candidate);
5945 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5946 return std::make_unique<FunctionCallCCC>(*this);
5949 private:
5950 const IdentifierInfo *const FunctionName;
5954 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5955 FunctionDecl *FDecl,
5956 ArrayRef<Expr *> Args) {
5957 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5958 DeclarationName FuncName = FDecl->getDeclName();
5959 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5961 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5962 if (TypoCorrection Corrected = S.CorrectTypo(
5963 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5964 S.getScopeForContext(S.CurContext), nullptr, CCC,
5965 Sema::CTK_ErrorRecovery)) {
5966 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5967 if (Corrected.isOverloaded()) {
5968 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5969 OverloadCandidateSet::iterator Best;
5970 for (NamedDecl *CD : Corrected) {
5971 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5972 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5973 OCS);
5975 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5976 case OR_Success:
5977 ND = Best->FoundDecl;
5978 Corrected.setCorrectionDecl(ND);
5979 break;
5980 default:
5981 break;
5984 ND = ND->getUnderlyingDecl();
5985 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5986 return Corrected;
5989 return TypoCorrection();
5992 /// ConvertArgumentsForCall - Converts the arguments specified in
5993 /// Args/NumArgs to the parameter types of the function FDecl with
5994 /// function prototype Proto. Call is the call expression itself, and
5995 /// Fn is the function expression. For a C++ member function, this
5996 /// routine does not attempt to convert the object argument. Returns
5997 /// true if the call is ill-formed.
5998 bool
5999 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
6000 FunctionDecl *FDecl,
6001 const FunctionProtoType *Proto,
6002 ArrayRef<Expr *> Args,
6003 SourceLocation RParenLoc,
6004 bool IsExecConfig) {
6005 // Bail out early if calling a builtin with custom typechecking.
6006 if (FDecl)
6007 if (unsigned ID = FDecl->getBuiltinID())
6008 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
6009 return false;
6011 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6012 // assignment, to the types of the corresponding parameter, ...
6013 unsigned NumParams = Proto->getNumParams();
6014 bool Invalid = false;
6015 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6016 unsigned FnKind = Fn->getType()->isBlockPointerType()
6017 ? 1 /* block */
6018 : (IsExecConfig ? 3 /* kernel function (exec config) */
6019 : 0 /* function */);
6021 // If too few arguments are available (and we don't have default
6022 // arguments for the remaining parameters), don't make the call.
6023 if (Args.size() < NumParams) {
6024 if (Args.size() < MinArgs) {
6025 TypoCorrection TC;
6026 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6027 unsigned diag_id =
6028 MinArgs == NumParams && !Proto->isVariadic()
6029 ? diag::err_typecheck_call_too_few_args_suggest
6030 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6031 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
6032 << static_cast<unsigned>(Args.size())
6033 << TC.getCorrectionRange());
6034 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
6035 Diag(RParenLoc,
6036 MinArgs == NumParams && !Proto->isVariadic()
6037 ? diag::err_typecheck_call_too_few_args_one
6038 : diag::err_typecheck_call_too_few_args_at_least_one)
6039 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
6040 else
6041 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6042 ? diag::err_typecheck_call_too_few_args
6043 : diag::err_typecheck_call_too_few_args_at_least)
6044 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
6045 << Fn->getSourceRange();
6047 // Emit the location of the prototype.
6048 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6049 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6051 return true;
6053 // We reserve space for the default arguments when we create
6054 // the call expression, before calling ConvertArgumentsForCall.
6055 assert((Call->getNumArgs() == NumParams) &&
6056 "We should have reserved space for the default arguments before!");
6059 // If too many are passed and not variadic, error on the extras and drop
6060 // them.
6061 if (Args.size() > NumParams) {
6062 if (!Proto->isVariadic()) {
6063 TypoCorrection TC;
6064 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6065 unsigned diag_id =
6066 MinArgs == NumParams && !Proto->isVariadic()
6067 ? diag::err_typecheck_call_too_many_args_suggest
6068 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6069 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
6070 << static_cast<unsigned>(Args.size())
6071 << TC.getCorrectionRange());
6072 } else if (NumParams == 1 && FDecl &&
6073 FDecl->getParamDecl(0)->getDeclName())
6074 Diag(Args[NumParams]->getBeginLoc(),
6075 MinArgs == NumParams
6076 ? diag::err_typecheck_call_too_many_args_one
6077 : diag::err_typecheck_call_too_many_args_at_most_one)
6078 << FnKind << FDecl->getParamDecl(0)
6079 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
6080 << SourceRange(Args[NumParams]->getBeginLoc(),
6081 Args.back()->getEndLoc());
6082 else
6083 Diag(Args[NumParams]->getBeginLoc(),
6084 MinArgs == NumParams
6085 ? diag::err_typecheck_call_too_many_args
6086 : diag::err_typecheck_call_too_many_args_at_most)
6087 << FnKind << NumParams << static_cast<unsigned>(Args.size())
6088 << Fn->getSourceRange()
6089 << SourceRange(Args[NumParams]->getBeginLoc(),
6090 Args.back()->getEndLoc());
6092 // Emit the location of the prototype.
6093 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6094 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6096 // This deletes the extra arguments.
6097 Call->shrinkNumArgs(NumParams);
6098 return true;
6101 SmallVector<Expr *, 8> AllArgs;
6102 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6104 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
6105 AllArgs, CallType);
6106 if (Invalid)
6107 return true;
6108 unsigned TotalNumArgs = AllArgs.size();
6109 for (unsigned i = 0; i < TotalNumArgs; ++i)
6110 Call->setArg(i, AllArgs[i]);
6112 Call->computeDependence();
6113 return false;
6116 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6117 const FunctionProtoType *Proto,
6118 unsigned FirstParam, ArrayRef<Expr *> Args,
6119 SmallVectorImpl<Expr *> &AllArgs,
6120 VariadicCallType CallType, bool AllowExplicit,
6121 bool IsListInitialization) {
6122 unsigned NumParams = Proto->getNumParams();
6123 bool Invalid = false;
6124 size_t ArgIx = 0;
6125 // Continue to check argument types (even if we have too few/many args).
6126 for (unsigned i = FirstParam; i < NumParams; i++) {
6127 QualType ProtoArgType = Proto->getParamType(i);
6129 Expr *Arg;
6130 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6131 if (ArgIx < Args.size()) {
6132 Arg = Args[ArgIx++];
6134 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6135 diag::err_call_incomplete_argument, Arg))
6136 return true;
6138 // Strip the unbridged-cast placeholder expression off, if applicable.
6139 bool CFAudited = false;
6140 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6141 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6142 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6143 Arg = stripARCUnbridgedCast(Arg);
6144 else if (getLangOpts().ObjCAutoRefCount &&
6145 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6146 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6147 CFAudited = true;
6149 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6150 ProtoArgType->isBlockPointerType())
6151 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6152 BE->getBlockDecl()->setDoesNotEscape();
6154 InitializedEntity Entity =
6155 Param ? InitializedEntity::InitializeParameter(Context, Param,
6156 ProtoArgType)
6157 : InitializedEntity::InitializeParameter(
6158 Context, ProtoArgType, Proto->isParamConsumed(i));
6160 // Remember that parameter belongs to a CF audited API.
6161 if (CFAudited)
6162 Entity.setParameterCFAudited();
6164 ExprResult ArgE = PerformCopyInitialization(
6165 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6166 if (ArgE.isInvalid())
6167 return true;
6169 Arg = ArgE.getAs<Expr>();
6170 } else {
6171 assert(Param && "can't use default arguments without a known callee");
6173 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6174 if (ArgExpr.isInvalid())
6175 return true;
6177 Arg = ArgExpr.getAs<Expr>();
6180 // Check for array bounds violations for each argument to the call. This
6181 // check only triggers warnings when the argument isn't a more complex Expr
6182 // with its own checking, such as a BinaryOperator.
6183 CheckArrayAccess(Arg);
6185 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6186 CheckStaticArrayArgument(CallLoc, Param, Arg);
6188 AllArgs.push_back(Arg);
6191 // If this is a variadic call, handle args passed through "...".
6192 if (CallType != VariadicDoesNotApply) {
6193 // Assume that extern "C" functions with variadic arguments that
6194 // return __unknown_anytype aren't *really* variadic.
6195 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6196 FDecl->isExternC()) {
6197 for (Expr *A : Args.slice(ArgIx)) {
6198 QualType paramType; // ignored
6199 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6200 Invalid |= arg.isInvalid();
6201 AllArgs.push_back(arg.get());
6204 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6205 } else {
6206 for (Expr *A : Args.slice(ArgIx)) {
6207 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6208 Invalid |= Arg.isInvalid();
6209 AllArgs.push_back(Arg.get());
6213 // Check for array bounds violations.
6214 for (Expr *A : Args.slice(ArgIx))
6215 CheckArrayAccess(A);
6217 return Invalid;
6220 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6221 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6222 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6223 TL = DTL.getOriginalLoc();
6224 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6225 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6226 << ATL.getLocalSourceRange();
6229 /// CheckStaticArrayArgument - If the given argument corresponds to a static
6230 /// array parameter, check that it is non-null, and that if it is formed by
6231 /// array-to-pointer decay, the underlying array is sufficiently large.
6233 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6234 /// array type derivation, then for each call to the function, the value of the
6235 /// corresponding actual argument shall provide access to the first element of
6236 /// an array with at least as many elements as specified by the size expression.
6237 void
6238 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6239 ParmVarDecl *Param,
6240 const Expr *ArgExpr) {
6241 // Static array parameters are not supported in C++.
6242 if (!Param || getLangOpts().CPlusPlus)
6243 return;
6245 QualType OrigTy = Param->getOriginalType();
6247 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6248 if (!AT || AT->getSizeModifier() != ArrayType::Static)
6249 return;
6251 if (ArgExpr->isNullPointerConstant(Context,
6252 Expr::NPC_NeverValueDependent)) {
6253 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6254 DiagnoseCalleeStaticArrayParam(*this, Param);
6255 return;
6258 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6259 if (!CAT)
6260 return;
6262 const ConstantArrayType *ArgCAT =
6263 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6264 if (!ArgCAT)
6265 return;
6267 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6268 ArgCAT->getElementType())) {
6269 if (ArgCAT->getSize().ult(CAT->getSize())) {
6270 Diag(CallLoc, diag::warn_static_array_too_small)
6271 << ArgExpr->getSourceRange()
6272 << (unsigned)ArgCAT->getSize().getZExtValue()
6273 << (unsigned)CAT->getSize().getZExtValue() << 0;
6274 DiagnoseCalleeStaticArrayParam(*this, Param);
6276 return;
6279 Optional<CharUnits> ArgSize =
6280 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6281 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6282 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6283 Diag(CallLoc, diag::warn_static_array_too_small)
6284 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6285 << (unsigned)ParmSize->getQuantity() << 1;
6286 DiagnoseCalleeStaticArrayParam(*this, Param);
6290 /// Given a function expression of unknown-any type, try to rebuild it
6291 /// to have a function type.
6292 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6294 /// Is the given type a placeholder that we need to lower out
6295 /// immediately during argument processing?
6296 static bool isPlaceholderToRemoveAsArg(QualType type) {
6297 // Placeholders are never sugared.
6298 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6299 if (!placeholder) return false;
6301 switch (placeholder->getKind()) {
6302 // Ignore all the non-placeholder types.
6303 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6304 case BuiltinType::Id:
6305 #include "clang/Basic/OpenCLImageTypes.def"
6306 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6307 case BuiltinType::Id:
6308 #include "clang/Basic/OpenCLExtensionTypes.def"
6309 // In practice we'll never use this, since all SVE types are sugared
6310 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6311 #define SVE_TYPE(Name, Id, SingletonId) \
6312 case BuiltinType::Id:
6313 #include "clang/Basic/AArch64SVEACLETypes.def"
6314 #define PPC_VECTOR_TYPE(Name, Id, Size) \
6315 case BuiltinType::Id:
6316 #include "clang/Basic/PPCTypes.def"
6317 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6318 #include "clang/Basic/RISCVVTypes.def"
6319 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6320 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6321 #include "clang/AST/BuiltinTypes.def"
6322 return false;
6324 // We cannot lower out overload sets; they might validly be resolved
6325 // by the call machinery.
6326 case BuiltinType::Overload:
6327 return false;
6329 // Unbridged casts in ARC can be handled in some call positions and
6330 // should be left in place.
6331 case BuiltinType::ARCUnbridgedCast:
6332 return false;
6334 // Pseudo-objects should be converted as soon as possible.
6335 case BuiltinType::PseudoObject:
6336 return true;
6338 // The debugger mode could theoretically but currently does not try
6339 // to resolve unknown-typed arguments based on known parameter types.
6340 case BuiltinType::UnknownAny:
6341 return true;
6343 // These are always invalid as call arguments and should be reported.
6344 case BuiltinType::BoundMember:
6345 case BuiltinType::BuiltinFn:
6346 case BuiltinType::IncompleteMatrixIdx:
6347 case BuiltinType::OMPArraySection:
6348 case BuiltinType::OMPArrayShaping:
6349 case BuiltinType::OMPIterator:
6350 return true;
6353 llvm_unreachable("bad builtin type kind");
6356 /// Check an argument list for placeholders that we won't try to
6357 /// handle later.
6358 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6359 // Apply this processing to all the arguments at once instead of
6360 // dying at the first failure.
6361 bool hasInvalid = false;
6362 for (size_t i = 0, e = args.size(); i != e; i++) {
6363 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6364 ExprResult result = S.CheckPlaceholderExpr(args[i]);
6365 if (result.isInvalid()) hasInvalid = true;
6366 else args[i] = result.get();
6369 return hasInvalid;
6372 /// If a builtin function has a pointer argument with no explicit address
6373 /// space, then it should be able to accept a pointer to any address
6374 /// space as input. In order to do this, we need to replace the
6375 /// standard builtin declaration with one that uses the same address space
6376 /// as the call.
6378 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6379 /// it does not contain any pointer arguments without
6380 /// an address space qualifer. Otherwise the rewritten
6381 /// FunctionDecl is returned.
6382 /// TODO: Handle pointer return types.
6383 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6384 FunctionDecl *FDecl,
6385 MultiExprArg ArgExprs) {
6387 QualType DeclType = FDecl->getType();
6388 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6390 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6391 ArgExprs.size() < FT->getNumParams())
6392 return nullptr;
6394 bool NeedsNewDecl = false;
6395 unsigned i = 0;
6396 SmallVector<QualType, 8> OverloadParams;
6398 for (QualType ParamType : FT->param_types()) {
6400 // Convert array arguments to pointer to simplify type lookup.
6401 ExprResult ArgRes =
6402 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6403 if (ArgRes.isInvalid())
6404 return nullptr;
6405 Expr *Arg = ArgRes.get();
6406 QualType ArgType = Arg->getType();
6407 if (!ParamType->isPointerType() ||
6408 ParamType.hasAddressSpace() ||
6409 !ArgType->isPointerType() ||
6410 !ArgType->getPointeeType().hasAddressSpace()) {
6411 OverloadParams.push_back(ParamType);
6412 continue;
6415 QualType PointeeType = ParamType->getPointeeType();
6416 if (PointeeType.hasAddressSpace())
6417 continue;
6419 NeedsNewDecl = true;
6420 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6422 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6423 OverloadParams.push_back(Context.getPointerType(PointeeType));
6426 if (!NeedsNewDecl)
6427 return nullptr;
6429 FunctionProtoType::ExtProtoInfo EPI;
6430 EPI.Variadic = FT->isVariadic();
6431 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6432 OverloadParams, EPI);
6433 DeclContext *Parent = FDecl->getParent();
6434 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6435 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6436 FDecl->getIdentifier(), OverloadTy,
6437 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6438 false,
6439 /*hasPrototype=*/true);
6440 SmallVector<ParmVarDecl*, 16> Params;
6441 FT = cast<FunctionProtoType>(OverloadTy);
6442 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6443 QualType ParamType = FT->getParamType(i);
6444 ParmVarDecl *Parm =
6445 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6446 SourceLocation(), nullptr, ParamType,
6447 /*TInfo=*/nullptr, SC_None, nullptr);
6448 Parm->setScopeInfo(0, i);
6449 Params.push_back(Parm);
6451 OverloadDecl->setParams(Params);
6452 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6453 return OverloadDecl;
6456 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6457 FunctionDecl *Callee,
6458 MultiExprArg ArgExprs) {
6459 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6460 // similar attributes) really don't like it when functions are called with an
6461 // invalid number of args.
6462 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6463 /*PartialOverloading=*/false) &&
6464 !Callee->isVariadic())
6465 return;
6466 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6467 return;
6469 if (const EnableIfAttr *Attr =
6470 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6471 S.Diag(Fn->getBeginLoc(),
6472 isa<CXXMethodDecl>(Callee)
6473 ? diag::err_ovl_no_viable_member_function_in_call
6474 : diag::err_ovl_no_viable_function_in_call)
6475 << Callee << Callee->getSourceRange();
6476 S.Diag(Callee->getLocation(),
6477 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6478 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6479 return;
6483 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6484 const UnresolvedMemberExpr *const UME, Sema &S) {
6486 const auto GetFunctionLevelDCIfCXXClass =
6487 [](Sema &S) -> const CXXRecordDecl * {
6488 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6489 if (!DC || !DC->getParent())
6490 return nullptr;
6492 // If the call to some member function was made from within a member
6493 // function body 'M' return return 'M's parent.
6494 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6495 return MD->getParent()->getCanonicalDecl();
6496 // else the call was made from within a default member initializer of a
6497 // class, so return the class.
6498 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6499 return RD->getCanonicalDecl();
6500 return nullptr;
6502 // If our DeclContext is neither a member function nor a class (in the
6503 // case of a lambda in a default member initializer), we can't have an
6504 // enclosing 'this'.
6506 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6507 if (!CurParentClass)
6508 return false;
6510 // The naming class for implicit member functions call is the class in which
6511 // name lookup starts.
6512 const CXXRecordDecl *const NamingClass =
6513 UME->getNamingClass()->getCanonicalDecl();
6514 assert(NamingClass && "Must have naming class even for implicit access");
6516 // If the unresolved member functions were found in a 'naming class' that is
6517 // related (either the same or derived from) to the class that contains the
6518 // member function that itself contained the implicit member access.
6520 return CurParentClass == NamingClass ||
6521 CurParentClass->isDerivedFrom(NamingClass);
6524 static void
6525 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6526 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6528 if (!UME)
6529 return;
6531 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6532 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6533 // already been captured, or if this is an implicit member function call (if
6534 // it isn't, an attempt to capture 'this' should already have been made).
6535 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6536 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6537 return;
6539 // Check if the naming class in which the unresolved members were found is
6540 // related (same as or is a base of) to the enclosing class.
6542 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6543 return;
6546 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6547 // If the enclosing function is not dependent, then this lambda is
6548 // capture ready, so if we can capture this, do so.
6549 if (!EnclosingFunctionCtx->isDependentContext()) {
6550 // If the current lambda and all enclosing lambdas can capture 'this' -
6551 // then go ahead and capture 'this' (since our unresolved overload set
6552 // contains at least one non-static member function).
6553 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6554 S.CheckCXXThisCapture(CallLoc);
6555 } else if (S.CurContext->isDependentContext()) {
6556 // ... since this is an implicit member reference, that might potentially
6557 // involve a 'this' capture, mark 'this' for potential capture in
6558 // enclosing lambdas.
6559 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6560 CurLSI->addPotentialThisCapture(CallLoc);
6564 // Once a call is fully resolved, warn for unqualified calls to specific
6565 // C++ standard functions, like move and forward.
6566 static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call) {
6567 // We are only checking unary move and forward so exit early here.
6568 if (Call->getNumArgs() != 1)
6569 return;
6571 Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6572 if (!E || isa<UnresolvedLookupExpr>(E))
6573 return;
6574 DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E);
6575 if (!DRE || !DRE->getLocation().isValid())
6576 return;
6578 if (DRE->getQualifier())
6579 return;
6581 const FunctionDecl *FD = Call->getDirectCallee();
6582 if (!FD)
6583 return;
6585 // Only warn for some functions deemed more frequent or problematic.
6586 unsigned BuiltinID = FD->getBuiltinID();
6587 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6588 return;
6590 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6591 << FD->getQualifiedNameAsString()
6592 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6595 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6596 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6597 Expr *ExecConfig) {
6598 ExprResult Call =
6599 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6600 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6601 if (Call.isInvalid())
6602 return Call;
6604 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6605 // language modes.
6606 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6607 if (ULE->hasExplicitTemplateArgs() &&
6608 ULE->decls_begin() == ULE->decls_end()) {
6609 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6610 ? diag::warn_cxx17_compat_adl_only_template_id
6611 : diag::ext_adl_only_template_id)
6612 << ULE->getName();
6616 if (LangOpts.OpenMP)
6617 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6618 ExecConfig);
6619 if (LangOpts.CPlusPlus) {
6620 CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6621 if (CE)
6622 DiagnosedUnqualifiedCallsToStdFunctions(*this, CE);
6624 return Call;
6627 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6628 /// This provides the location of the left/right parens and a list of comma
6629 /// locations.
6630 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6631 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6632 Expr *ExecConfig, bool IsExecConfig,
6633 bool AllowRecovery) {
6634 // Since this might be a postfix expression, get rid of ParenListExprs.
6635 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6636 if (Result.isInvalid()) return ExprError();
6637 Fn = Result.get();
6639 if (checkArgsForPlaceholders(*this, ArgExprs))
6640 return ExprError();
6642 if (getLangOpts().CPlusPlus) {
6643 // If this is a pseudo-destructor expression, build the call immediately.
6644 if (isa<CXXPseudoDestructorExpr>(Fn)) {
6645 if (!ArgExprs.empty()) {
6646 // Pseudo-destructor calls should not have any arguments.
6647 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6648 << FixItHint::CreateRemoval(
6649 SourceRange(ArgExprs.front()->getBeginLoc(),
6650 ArgExprs.back()->getEndLoc()));
6653 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6654 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6656 if (Fn->getType() == Context.PseudoObjectTy) {
6657 ExprResult result = CheckPlaceholderExpr(Fn);
6658 if (result.isInvalid()) return ExprError();
6659 Fn = result.get();
6662 // Determine whether this is a dependent call inside a C++ template,
6663 // in which case we won't do any semantic analysis now.
6664 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6665 if (ExecConfig) {
6666 return CUDAKernelCallExpr::Create(Context, Fn,
6667 cast<CallExpr>(ExecConfig), ArgExprs,
6668 Context.DependentTy, VK_PRValue,
6669 RParenLoc, CurFPFeatureOverrides());
6670 } else {
6672 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6673 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6674 Fn->getBeginLoc());
6676 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6677 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6681 // Determine whether this is a call to an object (C++ [over.call.object]).
6682 if (Fn->getType()->isRecordType())
6683 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6684 RParenLoc);
6686 if (Fn->getType() == Context.UnknownAnyTy) {
6687 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6688 if (result.isInvalid()) return ExprError();
6689 Fn = result.get();
6692 if (Fn->getType() == Context.BoundMemberTy) {
6693 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6694 RParenLoc, ExecConfig, IsExecConfig,
6695 AllowRecovery);
6699 // Check for overloaded calls. This can happen even in C due to extensions.
6700 if (Fn->getType() == Context.OverloadTy) {
6701 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6703 // We aren't supposed to apply this logic if there's an '&' involved.
6704 if (!find.HasFormOfMemberPointer) {
6705 if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6706 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6707 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6708 OverloadExpr *ovl = find.Expression;
6709 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6710 return BuildOverloadedCallExpr(
6711 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6712 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6713 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6714 RParenLoc, ExecConfig, IsExecConfig,
6715 AllowRecovery);
6719 // If we're directly calling a function, get the appropriate declaration.
6720 if (Fn->getType() == Context.UnknownAnyTy) {
6721 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6722 if (result.isInvalid()) return ExprError();
6723 Fn = result.get();
6726 Expr *NakedFn = Fn->IgnoreParens();
6728 bool CallingNDeclIndirectly = false;
6729 NamedDecl *NDecl = nullptr;
6730 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6731 if (UnOp->getOpcode() == UO_AddrOf) {
6732 CallingNDeclIndirectly = true;
6733 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6737 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6738 NDecl = DRE->getDecl();
6740 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6741 if (FDecl && FDecl->getBuiltinID()) {
6742 // Rewrite the function decl for this builtin by replacing parameters
6743 // with no explicit address space with the address space of the arguments
6744 // in ArgExprs.
6745 if ((FDecl =
6746 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6747 NDecl = FDecl;
6748 Fn = DeclRefExpr::Create(
6749 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6750 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6751 nullptr, DRE->isNonOdrUse());
6754 } else if (isa<MemberExpr>(NakedFn))
6755 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6757 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6758 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6759 FD, /*Complain=*/true, Fn->getBeginLoc()))
6760 return ExprError();
6762 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6764 // If this expression is a call to a builtin function in HIP device
6765 // compilation, allow a pointer-type argument to default address space to be
6766 // passed as a pointer-type parameter to a non-default address space.
6767 // If Arg is declared in the default address space and Param is declared
6768 // in a non-default address space, perform an implicit address space cast to
6769 // the parameter type.
6770 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6771 FD->getBuiltinID()) {
6772 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
6773 ParmVarDecl *Param = FD->getParamDecl(Idx);
6774 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6775 !ArgExprs[Idx]->getType()->isPointerType())
6776 continue;
6778 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6779 auto ArgTy = ArgExprs[Idx]->getType();
6780 auto ArgPtTy = ArgTy->getPointeeType();
6781 auto ArgAS = ArgPtTy.getAddressSpace();
6783 // Add address space cast if target address spaces are different
6784 bool NeedImplicitASC =
6785 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6786 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6787 // or from specific AS which has target AS matching that of Param.
6788 getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));
6789 if (!NeedImplicitASC)
6790 continue;
6792 // First, ensure that the Arg is an RValue.
6793 if (ArgExprs[Idx]->isGLValue()) {
6794 ArgExprs[Idx] = ImplicitCastExpr::Create(
6795 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6796 nullptr, VK_PRValue, FPOptionsOverride());
6799 // Construct a new arg type with address space of Param
6800 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6801 ArgPtQuals.setAddressSpace(ParamAS);
6802 auto NewArgPtTy =
6803 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6804 auto NewArgTy =
6805 Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
6806 ArgTy.getQualifiers());
6808 // Finally perform an implicit address space cast
6809 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6810 CK_AddressSpaceConversion)
6811 .get();
6816 if (Context.isDependenceAllowed() &&
6817 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6818 assert(!getLangOpts().CPlusPlus);
6819 assert((Fn->containsErrors() ||
6820 llvm::any_of(ArgExprs,
6821 [](clang::Expr *E) { return E->containsErrors(); })) &&
6822 "should only occur in error-recovery path.");
6823 QualType ReturnType =
6824 llvm::isa_and_nonnull<FunctionDecl>(NDecl)
6825 ? cast<FunctionDecl>(NDecl)->getCallResultType()
6826 : Context.DependentTy;
6827 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
6828 Expr::getValueKindForType(ReturnType), RParenLoc,
6829 CurFPFeatureOverrides());
6831 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6832 ExecConfig, IsExecConfig);
6835 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
6836 // with the specified CallArgs
6837 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
6838 MultiExprArg CallArgs) {
6839 StringRef Name = Context.BuiltinInfo.getName(Id);
6840 LookupResult R(*this, &Context.Idents.get(Name), Loc,
6841 Sema::LookupOrdinaryName);
6842 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6844 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6845 assert(BuiltInDecl && "failed to find builtin declaration");
6847 ExprResult DeclRef =
6848 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6849 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6851 ExprResult Call =
6852 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6854 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6855 return Call.get();
6858 /// Parse a __builtin_astype expression.
6860 /// __builtin_astype( value, dst type )
6862 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6863 SourceLocation BuiltinLoc,
6864 SourceLocation RParenLoc) {
6865 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6866 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6869 /// Create a new AsTypeExpr node (bitcast) from the arguments.
6870 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
6871 SourceLocation BuiltinLoc,
6872 SourceLocation RParenLoc) {
6873 ExprValueKind VK = VK_PRValue;
6874 ExprObjectKind OK = OK_Ordinary;
6875 QualType SrcTy = E->getType();
6876 if (!SrcTy->isDependentType() &&
6877 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6878 return ExprError(
6879 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6880 << DestTy << SrcTy << E->getSourceRange());
6881 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6884 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6885 /// provided arguments.
6887 /// __builtin_convertvector( value, dst type )
6889 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6890 SourceLocation BuiltinLoc,
6891 SourceLocation RParenLoc) {
6892 TypeSourceInfo *TInfo;
6893 GetTypeFromParser(ParsedDestTy, &TInfo);
6894 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6897 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6898 /// i.e. an expression not of \p OverloadTy. The expression should
6899 /// unary-convert to an expression of function-pointer or
6900 /// block-pointer type.
6902 /// \param NDecl the declaration being called, if available
6903 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6904 SourceLocation LParenLoc,
6905 ArrayRef<Expr *> Args,
6906 SourceLocation RParenLoc, Expr *Config,
6907 bool IsExecConfig, ADLCallKind UsesADL) {
6908 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6909 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6911 // Functions with 'interrupt' attribute cannot be called directly.
6912 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6913 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6914 return ExprError();
6917 // Interrupt handlers don't save off the VFP regs automatically on ARM,
6918 // so there's some risk when calling out to non-interrupt handler functions
6919 // that the callee might not preserve them. This is easy to diagnose here,
6920 // but can be very challenging to debug.
6921 // Likewise, X86 interrupt handlers may only call routines with attribute
6922 // no_caller_saved_registers since there is no efficient way to
6923 // save and restore the non-GPR state.
6924 if (auto *Caller = getCurFunctionDecl()) {
6925 if (Caller->hasAttr<ARMInterruptAttr>()) {
6926 bool VFP = Context.getTargetInfo().hasFeature("vfp");
6927 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
6928 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6929 if (FDecl)
6930 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6933 if (Caller->hasAttr<AnyX86InterruptAttr>() &&
6934 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
6935 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
6936 if (FDecl)
6937 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6941 // Promote the function operand.
6942 // We special-case function promotion here because we only allow promoting
6943 // builtin functions to function pointers in the callee of a call.
6944 ExprResult Result;
6945 QualType ResultTy;
6946 if (BuiltinID &&
6947 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6948 // Extract the return type from the (builtin) function pointer type.
6949 // FIXME Several builtins still have setType in
6950 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6951 // Builtins.def to ensure they are correct before removing setType calls.
6952 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6953 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6954 ResultTy = FDecl->getCallResultType();
6955 } else {
6956 Result = CallExprUnaryConversions(Fn);
6957 ResultTy = Context.BoolTy;
6959 if (Result.isInvalid())
6960 return ExprError();
6961 Fn = Result.get();
6963 // Check for a valid function type, but only if it is not a builtin which
6964 // requires custom type checking. These will be handled by
6965 // CheckBuiltinFunctionCall below just after creation of the call expression.
6966 const FunctionType *FuncT = nullptr;
6967 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6968 retry:
6969 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6970 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6971 // have type pointer to function".
6972 FuncT = PT->getPointeeType()->getAs<FunctionType>();
6973 if (!FuncT)
6974 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6975 << Fn->getType() << Fn->getSourceRange());
6976 } else if (const BlockPointerType *BPT =
6977 Fn->getType()->getAs<BlockPointerType>()) {
6978 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6979 } else {
6980 // Handle calls to expressions of unknown-any type.
6981 if (Fn->getType() == Context.UnknownAnyTy) {
6982 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6983 if (rewrite.isInvalid())
6984 return ExprError();
6985 Fn = rewrite.get();
6986 goto retry;
6989 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6990 << Fn->getType() << Fn->getSourceRange());
6994 // Get the number of parameters in the function prototype, if any.
6995 // We will allocate space for max(Args.size(), NumParams) arguments
6996 // in the call expression.
6997 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6998 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7000 CallExpr *TheCall;
7001 if (Config) {
7002 assert(UsesADL == ADLCallKind::NotADL &&
7003 "CUDAKernelCallExpr should not use ADL");
7004 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
7005 Args, ResultTy, VK_PRValue, RParenLoc,
7006 CurFPFeatureOverrides(), NumParams);
7007 } else {
7008 TheCall =
7009 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7010 CurFPFeatureOverrides(), NumParams, UsesADL);
7013 if (!Context.isDependenceAllowed()) {
7014 // Forget about the nulled arguments since typo correction
7015 // do not handle them well.
7016 TheCall->shrinkNumArgs(Args.size());
7017 // C cannot always handle TypoExpr nodes in builtin calls and direct
7018 // function calls as their argument checking don't necessarily handle
7019 // dependent types properly, so make sure any TypoExprs have been
7020 // dealt with.
7021 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
7022 if (!Result.isUsable()) return ExprError();
7023 CallExpr *TheOldCall = TheCall;
7024 TheCall = dyn_cast<CallExpr>(Result.get());
7025 bool CorrectedTypos = TheCall != TheOldCall;
7026 if (!TheCall) return Result;
7027 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
7029 // A new call expression node was created if some typos were corrected.
7030 // However it may not have been constructed with enough storage. In this
7031 // case, rebuild the node with enough storage. The waste of space is
7032 // immaterial since this only happens when some typos were corrected.
7033 if (CorrectedTypos && Args.size() < NumParams) {
7034 if (Config)
7035 TheCall = CUDAKernelCallExpr::Create(
7036 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
7037 RParenLoc, CurFPFeatureOverrides(), NumParams);
7038 else
7039 TheCall =
7040 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7041 CurFPFeatureOverrides(), NumParams, UsesADL);
7043 // We can now handle the nulled arguments for the default arguments.
7044 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
7047 // Bail out early if calling a builtin with custom type checking.
7048 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
7049 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7051 if (getLangOpts().CUDA) {
7052 if (Config) {
7053 // CUDA: Kernel calls must be to global functions
7054 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7055 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7056 << FDecl << Fn->getSourceRange());
7058 // CUDA: Kernel function must have 'void' return type
7059 if (!FuncT->getReturnType()->isVoidType() &&
7060 !FuncT->getReturnType()->getAs<AutoType>() &&
7061 !FuncT->getReturnType()->isInstantiationDependentType())
7062 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7063 << Fn->getType() << Fn->getSourceRange());
7064 } else {
7065 // CUDA: Calls to global functions must be configured
7066 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7067 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7068 << FDecl << Fn->getSourceRange());
7072 // Check for a valid return type
7073 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7074 FDecl))
7075 return ExprError();
7077 // We know the result type of the call, set it.
7078 TheCall->setType(FuncT->getCallResultType(Context));
7079 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
7081 if (Proto) {
7082 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7083 IsExecConfig))
7084 return ExprError();
7085 } else {
7086 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7088 if (FDecl) {
7089 // Check if we have too few/too many template arguments, based
7090 // on our knowledge of the function definition.
7091 const FunctionDecl *Def = nullptr;
7092 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7093 Proto = Def->getType()->getAs<FunctionProtoType>();
7094 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7095 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7096 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7099 // If the function we're calling isn't a function prototype, but we have
7100 // a function prototype from a prior declaratiom, use that prototype.
7101 if (!FDecl->hasPrototype())
7102 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7105 // If we still haven't found a prototype to use but there are arguments to
7106 // the call, diagnose this as calling a function without a prototype.
7107 // However, if we found a function declaration, check to see if
7108 // -Wdeprecated-non-prototype was disabled where the function was declared.
7109 // If so, we will silence the diagnostic here on the assumption that this
7110 // interface is intentional and the user knows what they're doing. We will
7111 // also silence the diagnostic if there is a function declaration but it
7112 // was implicitly defined (the user already gets diagnostics about the
7113 // creation of the implicit function declaration, so the additional warning
7114 // is not helpful).
7115 if (!Proto && !Args.empty() &&
7116 (!FDecl || (!FDecl->isImplicit() &&
7117 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7118 FDecl->getLocation()))))
7119 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7120 << (FDecl != nullptr) << FDecl;
7122 // Promote the arguments (C99 6.5.2.2p6).
7123 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7124 Expr *Arg = Args[i];
7126 if (Proto && i < Proto->getNumParams()) {
7127 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7128 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7129 ExprResult ArgE =
7130 PerformCopyInitialization(Entity, SourceLocation(), Arg);
7131 if (ArgE.isInvalid())
7132 return true;
7134 Arg = ArgE.getAs<Expr>();
7136 } else {
7137 ExprResult ArgE = DefaultArgumentPromotion(Arg);
7139 if (ArgE.isInvalid())
7140 return true;
7142 Arg = ArgE.getAs<Expr>();
7145 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7146 diag::err_call_incomplete_argument, Arg))
7147 return ExprError();
7149 TheCall->setArg(i, Arg);
7151 TheCall->computeDependence();
7154 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7155 if (!Method->isStatic())
7156 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7157 << Fn->getSourceRange());
7159 // Check for sentinels
7160 if (NDecl)
7161 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7163 // Warn for unions passing across security boundary (CMSE).
7164 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7165 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7166 if (const auto *RT =
7167 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7168 if (RT->getDecl()->isOrContainsUnion())
7169 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7170 << 0 << i;
7175 // Do special checking on direct calls to functions.
7176 if (FDecl) {
7177 if (CheckFunctionCall(FDecl, TheCall, Proto))
7178 return ExprError();
7180 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7182 if (BuiltinID)
7183 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7184 } else if (NDecl) {
7185 if (CheckPointerCall(NDecl, TheCall, Proto))
7186 return ExprError();
7187 } else {
7188 if (CheckOtherCall(TheCall, Proto))
7189 return ExprError();
7192 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7195 ExprResult
7196 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7197 SourceLocation RParenLoc, Expr *InitExpr) {
7198 assert(Ty && "ActOnCompoundLiteral(): missing type");
7199 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7201 TypeSourceInfo *TInfo;
7202 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7203 if (!TInfo)
7204 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7206 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7209 ExprResult
7210 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7211 SourceLocation RParenLoc, Expr *LiteralExpr) {
7212 QualType literalType = TInfo->getType();
7214 if (literalType->isArrayType()) {
7215 if (RequireCompleteSizedType(
7216 LParenLoc, Context.getBaseElementType(literalType),
7217 diag::err_array_incomplete_or_sizeless_type,
7218 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7219 return ExprError();
7220 if (literalType->isVariableArrayType()) {
7221 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7222 diag::err_variable_object_no_init)) {
7223 return ExprError();
7226 } else if (!literalType->isDependentType() &&
7227 RequireCompleteType(LParenLoc, literalType,
7228 diag::err_typecheck_decl_incomplete_type,
7229 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7230 return ExprError();
7232 InitializedEntity Entity
7233 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
7234 InitializationKind Kind
7235 = InitializationKind::CreateCStyleCast(LParenLoc,
7236 SourceRange(LParenLoc, RParenLoc),
7237 /*InitList=*/true);
7238 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7239 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7240 &literalType);
7241 if (Result.isInvalid())
7242 return ExprError();
7243 LiteralExpr = Result.get();
7245 bool isFileScope = !CurContext->isFunctionOrMethod();
7247 // In C, compound literals are l-values for some reason.
7248 // For GCC compatibility, in C++, file-scope array compound literals with
7249 // constant initializers are also l-values, and compound literals are
7250 // otherwise prvalues.
7252 // (GCC also treats C++ list-initialized file-scope array prvalues with
7253 // constant initializers as l-values, but that's non-conforming, so we don't
7254 // follow it there.)
7256 // FIXME: It would be better to handle the lvalue cases as materializing and
7257 // lifetime-extending a temporary object, but our materialized temporaries
7258 // representation only supports lifetime extension from a variable, not "out
7259 // of thin air".
7260 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7261 // is bound to the result of applying array-to-pointer decay to the compound
7262 // literal.
7263 // FIXME: GCC supports compound literals of reference type, which should
7264 // obviously have a value kind derived from the kind of reference involved.
7265 ExprValueKind VK =
7266 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7267 ? VK_PRValue
7268 : VK_LValue;
7270 if (isFileScope)
7271 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7272 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7273 Expr *Init = ILE->getInit(i);
7274 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7277 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7278 VK, LiteralExpr, isFileScope);
7279 if (isFileScope) {
7280 if (!LiteralExpr->isTypeDependent() &&
7281 !LiteralExpr->isValueDependent() &&
7282 !literalType->isDependentType()) // C99 6.5.2.5p3
7283 if (CheckForConstantInitializer(LiteralExpr, literalType))
7284 return ExprError();
7285 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7286 literalType.getAddressSpace() != LangAS::Default) {
7287 // Embedded-C extensions to C99 6.5.2.5:
7288 // "If the compound literal occurs inside the body of a function, the
7289 // type name shall not be qualified by an address-space qualifier."
7290 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7291 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7292 return ExprError();
7295 if (!isFileScope && !getLangOpts().CPlusPlus) {
7296 // Compound literals that have automatic storage duration are destroyed at
7297 // the end of the scope in C; in C++, they're just temporaries.
7299 // Emit diagnostics if it is or contains a C union type that is non-trivial
7300 // to destruct.
7301 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7302 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7303 NTCUC_CompoundLiteral, NTCUK_Destruct);
7305 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7306 if (literalType.isDestructedType()) {
7307 Cleanup.setExprNeedsCleanups(true);
7308 ExprCleanupObjects.push_back(E);
7309 getCurFunction()->setHasBranchProtectedScope();
7313 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7314 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7315 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7316 E->getInitializer()->getExprLoc());
7318 return MaybeBindToTemporary(E);
7321 ExprResult
7322 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7323 SourceLocation RBraceLoc) {
7324 // Only produce each kind of designated initialization diagnostic once.
7325 SourceLocation FirstDesignator;
7326 bool DiagnosedArrayDesignator = false;
7327 bool DiagnosedNestedDesignator = false;
7328 bool DiagnosedMixedDesignator = false;
7330 // Check that any designated initializers are syntactically valid in the
7331 // current language mode.
7332 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7333 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7334 if (FirstDesignator.isInvalid())
7335 FirstDesignator = DIE->getBeginLoc();
7337 if (!getLangOpts().CPlusPlus)
7338 break;
7340 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7341 DiagnosedNestedDesignator = true;
7342 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7343 << DIE->getDesignatorsSourceRange();
7346 for (auto &Desig : DIE->designators()) {
7347 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7348 DiagnosedArrayDesignator = true;
7349 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7350 << Desig.getSourceRange();
7354 if (!DiagnosedMixedDesignator &&
7355 !isa<DesignatedInitExpr>(InitArgList[0])) {
7356 DiagnosedMixedDesignator = true;
7357 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7358 << DIE->getSourceRange();
7359 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7360 << InitArgList[0]->getSourceRange();
7362 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7363 isa<DesignatedInitExpr>(InitArgList[0])) {
7364 DiagnosedMixedDesignator = true;
7365 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7366 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7367 << DIE->getSourceRange();
7368 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7369 << InitArgList[I]->getSourceRange();
7373 if (FirstDesignator.isValid()) {
7374 // Only diagnose designated initiaization as a C++20 extension if we didn't
7375 // already diagnose use of (non-C++20) C99 designator syntax.
7376 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7377 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7378 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7379 ? diag::warn_cxx17_compat_designated_init
7380 : diag::ext_cxx_designated_init);
7381 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7382 Diag(FirstDesignator, diag::ext_designated_init);
7386 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7389 ExprResult
7390 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7391 SourceLocation RBraceLoc) {
7392 // Semantic analysis for initializers is done by ActOnDeclarator() and
7393 // CheckInitializer() - it requires knowledge of the object being initialized.
7395 // Immediately handle non-overload placeholders. Overloads can be
7396 // resolved contextually, but everything else here can't.
7397 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7398 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7399 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7401 // Ignore failures; dropping the entire initializer list because
7402 // of one failure would be terrible for indexing/etc.
7403 if (result.isInvalid()) continue;
7405 InitArgList[I] = result.get();
7409 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7410 RBraceLoc);
7411 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7412 return E;
7415 /// Do an explicit extend of the given block pointer if we're in ARC.
7416 void Sema::maybeExtendBlockObject(ExprResult &E) {
7417 assert(E.get()->getType()->isBlockPointerType());
7418 assert(E.get()->isPRValue());
7420 // Only do this in an r-value context.
7421 if (!getLangOpts().ObjCAutoRefCount) return;
7423 E = ImplicitCastExpr::Create(
7424 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7425 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7426 Cleanup.setExprNeedsCleanups(true);
7429 /// Prepare a conversion of the given expression to an ObjC object
7430 /// pointer type.
7431 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7432 QualType type = E.get()->getType();
7433 if (type->isObjCObjectPointerType()) {
7434 return CK_BitCast;
7435 } else if (type->isBlockPointerType()) {
7436 maybeExtendBlockObject(E);
7437 return CK_BlockPointerToObjCPointerCast;
7438 } else {
7439 assert(type->isPointerType());
7440 return CK_CPointerToObjCPointerCast;
7444 /// Prepares for a scalar cast, performing all the necessary stages
7445 /// except the final cast and returning the kind required.
7446 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7447 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7448 // Also, callers should have filtered out the invalid cases with
7449 // pointers. Everything else should be possible.
7451 QualType SrcTy = Src.get()->getType();
7452 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7453 return CK_NoOp;
7455 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7456 case Type::STK_MemberPointer:
7457 llvm_unreachable("member pointer type in C");
7459 case Type::STK_CPointer:
7460 case Type::STK_BlockPointer:
7461 case Type::STK_ObjCObjectPointer:
7462 switch (DestTy->getScalarTypeKind()) {
7463 case Type::STK_CPointer: {
7464 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7465 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7466 if (SrcAS != DestAS)
7467 return CK_AddressSpaceConversion;
7468 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7469 return CK_NoOp;
7470 return CK_BitCast;
7472 case Type::STK_BlockPointer:
7473 return (SrcKind == Type::STK_BlockPointer
7474 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7475 case Type::STK_ObjCObjectPointer:
7476 if (SrcKind == Type::STK_ObjCObjectPointer)
7477 return CK_BitCast;
7478 if (SrcKind == Type::STK_CPointer)
7479 return CK_CPointerToObjCPointerCast;
7480 maybeExtendBlockObject(Src);
7481 return CK_BlockPointerToObjCPointerCast;
7482 case Type::STK_Bool:
7483 return CK_PointerToBoolean;
7484 case Type::STK_Integral:
7485 return CK_PointerToIntegral;
7486 case Type::STK_Floating:
7487 case Type::STK_FloatingComplex:
7488 case Type::STK_IntegralComplex:
7489 case Type::STK_MemberPointer:
7490 case Type::STK_FixedPoint:
7491 llvm_unreachable("illegal cast from pointer");
7493 llvm_unreachable("Should have returned before this");
7495 case Type::STK_FixedPoint:
7496 switch (DestTy->getScalarTypeKind()) {
7497 case Type::STK_FixedPoint:
7498 return CK_FixedPointCast;
7499 case Type::STK_Bool:
7500 return CK_FixedPointToBoolean;
7501 case Type::STK_Integral:
7502 return CK_FixedPointToIntegral;
7503 case Type::STK_Floating:
7504 return CK_FixedPointToFloating;
7505 case Type::STK_IntegralComplex:
7506 case Type::STK_FloatingComplex:
7507 Diag(Src.get()->getExprLoc(),
7508 diag::err_unimplemented_conversion_with_fixed_point_type)
7509 << DestTy;
7510 return CK_IntegralCast;
7511 case Type::STK_CPointer:
7512 case Type::STK_ObjCObjectPointer:
7513 case Type::STK_BlockPointer:
7514 case Type::STK_MemberPointer:
7515 llvm_unreachable("illegal cast to pointer type");
7517 llvm_unreachable("Should have returned before this");
7519 case Type::STK_Bool: // casting from bool is like casting from an integer
7520 case Type::STK_Integral:
7521 switch (DestTy->getScalarTypeKind()) {
7522 case Type::STK_CPointer:
7523 case Type::STK_ObjCObjectPointer:
7524 case Type::STK_BlockPointer:
7525 if (Src.get()->isNullPointerConstant(Context,
7526 Expr::NPC_ValueDependentIsNull))
7527 return CK_NullToPointer;
7528 return CK_IntegralToPointer;
7529 case Type::STK_Bool:
7530 return CK_IntegralToBoolean;
7531 case Type::STK_Integral:
7532 return CK_IntegralCast;
7533 case Type::STK_Floating:
7534 return CK_IntegralToFloating;
7535 case Type::STK_IntegralComplex:
7536 Src = ImpCastExprToType(Src.get(),
7537 DestTy->castAs<ComplexType>()->getElementType(),
7538 CK_IntegralCast);
7539 return CK_IntegralRealToComplex;
7540 case Type::STK_FloatingComplex:
7541 Src = ImpCastExprToType(Src.get(),
7542 DestTy->castAs<ComplexType>()->getElementType(),
7543 CK_IntegralToFloating);
7544 return CK_FloatingRealToComplex;
7545 case Type::STK_MemberPointer:
7546 llvm_unreachable("member pointer type in C");
7547 case Type::STK_FixedPoint:
7548 return CK_IntegralToFixedPoint;
7550 llvm_unreachable("Should have returned before this");
7552 case Type::STK_Floating:
7553 switch (DestTy->getScalarTypeKind()) {
7554 case Type::STK_Floating:
7555 return CK_FloatingCast;
7556 case Type::STK_Bool:
7557 return CK_FloatingToBoolean;
7558 case Type::STK_Integral:
7559 return CK_FloatingToIntegral;
7560 case Type::STK_FloatingComplex:
7561 Src = ImpCastExprToType(Src.get(),
7562 DestTy->castAs<ComplexType>()->getElementType(),
7563 CK_FloatingCast);
7564 return CK_FloatingRealToComplex;
7565 case Type::STK_IntegralComplex:
7566 Src = ImpCastExprToType(Src.get(),
7567 DestTy->castAs<ComplexType>()->getElementType(),
7568 CK_FloatingToIntegral);
7569 return CK_IntegralRealToComplex;
7570 case Type::STK_CPointer:
7571 case Type::STK_ObjCObjectPointer:
7572 case Type::STK_BlockPointer:
7573 llvm_unreachable("valid float->pointer cast?");
7574 case Type::STK_MemberPointer:
7575 llvm_unreachable("member pointer type in C");
7576 case Type::STK_FixedPoint:
7577 return CK_FloatingToFixedPoint;
7579 llvm_unreachable("Should have returned before this");
7581 case Type::STK_FloatingComplex:
7582 switch (DestTy->getScalarTypeKind()) {
7583 case Type::STK_FloatingComplex:
7584 return CK_FloatingComplexCast;
7585 case Type::STK_IntegralComplex:
7586 return CK_FloatingComplexToIntegralComplex;
7587 case Type::STK_Floating: {
7588 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7589 if (Context.hasSameType(ET, DestTy))
7590 return CK_FloatingComplexToReal;
7591 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7592 return CK_FloatingCast;
7594 case Type::STK_Bool:
7595 return CK_FloatingComplexToBoolean;
7596 case Type::STK_Integral:
7597 Src = ImpCastExprToType(Src.get(),
7598 SrcTy->castAs<ComplexType>()->getElementType(),
7599 CK_FloatingComplexToReal);
7600 return CK_FloatingToIntegral;
7601 case Type::STK_CPointer:
7602 case Type::STK_ObjCObjectPointer:
7603 case Type::STK_BlockPointer:
7604 llvm_unreachable("valid complex float->pointer cast?");
7605 case Type::STK_MemberPointer:
7606 llvm_unreachable("member pointer type in C");
7607 case Type::STK_FixedPoint:
7608 Diag(Src.get()->getExprLoc(),
7609 diag::err_unimplemented_conversion_with_fixed_point_type)
7610 << SrcTy;
7611 return CK_IntegralCast;
7613 llvm_unreachable("Should have returned before this");
7615 case Type::STK_IntegralComplex:
7616 switch (DestTy->getScalarTypeKind()) {
7617 case Type::STK_FloatingComplex:
7618 return CK_IntegralComplexToFloatingComplex;
7619 case Type::STK_IntegralComplex:
7620 return CK_IntegralComplexCast;
7621 case Type::STK_Integral: {
7622 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7623 if (Context.hasSameType(ET, DestTy))
7624 return CK_IntegralComplexToReal;
7625 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7626 return CK_IntegralCast;
7628 case Type::STK_Bool:
7629 return CK_IntegralComplexToBoolean;
7630 case Type::STK_Floating:
7631 Src = ImpCastExprToType(Src.get(),
7632 SrcTy->castAs<ComplexType>()->getElementType(),
7633 CK_IntegralComplexToReal);
7634 return CK_IntegralToFloating;
7635 case Type::STK_CPointer:
7636 case Type::STK_ObjCObjectPointer:
7637 case Type::STK_BlockPointer:
7638 llvm_unreachable("valid complex int->pointer cast?");
7639 case Type::STK_MemberPointer:
7640 llvm_unreachable("member pointer type in C");
7641 case Type::STK_FixedPoint:
7642 Diag(Src.get()->getExprLoc(),
7643 diag::err_unimplemented_conversion_with_fixed_point_type)
7644 << SrcTy;
7645 return CK_IntegralCast;
7647 llvm_unreachable("Should have returned before this");
7650 llvm_unreachable("Unhandled scalar cast");
7653 static bool breakDownVectorType(QualType type, uint64_t &len,
7654 QualType &eltType) {
7655 // Vectors are simple.
7656 if (const VectorType *vecType = type->getAs<VectorType>()) {
7657 len = vecType->getNumElements();
7658 eltType = vecType->getElementType();
7659 assert(eltType->isScalarType());
7660 return true;
7663 // We allow lax conversion to and from non-vector types, but only if
7664 // they're real types (i.e. non-complex, non-pointer scalar types).
7665 if (!type->isRealType()) return false;
7667 len = 1;
7668 eltType = type;
7669 return true;
7672 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7673 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7674 /// allowed?
7676 /// This will also return false if the two given types do not make sense from
7677 /// the perspective of SVE bitcasts.
7678 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7679 assert(srcTy->isVectorType() || destTy->isVectorType());
7681 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7682 if (!FirstType->isSizelessBuiltinType())
7683 return false;
7685 const auto *VecTy = SecondType->getAs<VectorType>();
7686 return VecTy &&
7687 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7690 return ValidScalableConversion(srcTy, destTy) ||
7691 ValidScalableConversion(destTy, srcTy);
7694 /// Are the two types matrix types and do they have the same dimensions i.e.
7695 /// do they have the same number of rows and the same number of columns?
7696 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7697 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7698 return false;
7700 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7701 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7703 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7704 matSrcType->getNumColumns() == matDestType->getNumColumns();
7707 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7708 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7710 uint64_t SrcLen, DestLen;
7711 QualType SrcEltTy, DestEltTy;
7712 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7713 return false;
7714 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7715 return false;
7717 // ASTContext::getTypeSize will return the size rounded up to a
7718 // power of 2, so instead of using that, we need to use the raw
7719 // element size multiplied by the element count.
7720 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7721 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7723 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7726 // This returns true if at least one of the types is an altivec vector.
7727 bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {
7728 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7729 "expected at least one type to be a vector here");
7731 bool IsSrcTyAltivec =
7732 SrcTy->isVectorType() && (SrcTy->castAs<VectorType>()->getVectorKind() ==
7733 VectorType::AltiVecVector);
7734 bool IsDestTyAltivec = DestTy->isVectorType() &&
7735 (DestTy->castAs<VectorType>()->getVectorKind() ==
7736 VectorType::AltiVecVector);
7738 return (IsSrcTyAltivec || IsDestTyAltivec);
7741 // This returns true if both vectors have the same element type.
7742 bool Sema::areSameVectorElemTypes(QualType SrcTy, QualType DestTy) {
7743 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7744 "expected at least one type to be a vector here");
7746 uint64_t SrcLen, DestLen;
7747 QualType SrcEltTy, DestEltTy;
7748 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7749 return false;
7750 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7751 return false;
7753 return (SrcEltTy == DestEltTy);
7756 /// Are the two types lax-compatible vector types? That is, given
7757 /// that one of them is a vector, do they have equal storage sizes,
7758 /// where the storage size is the number of elements times the element
7759 /// size?
7761 /// This will also return false if either of the types is neither a
7762 /// vector nor a real type.
7763 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7764 assert(destTy->isVectorType() || srcTy->isVectorType());
7766 // Disallow lax conversions between scalars and ExtVectors (these
7767 // conversions are allowed for other vector types because common headers
7768 // depend on them). Most scalar OP ExtVector cases are handled by the
7769 // splat path anyway, which does what we want (convert, not bitcast).
7770 // What this rules out for ExtVectors is crazy things like char4*float.
7771 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7772 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7774 return areVectorTypesSameSize(srcTy, destTy);
7777 /// Is this a legal conversion between two types, one of which is
7778 /// known to be a vector type?
7779 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7780 assert(destTy->isVectorType() || srcTy->isVectorType());
7782 switch (Context.getLangOpts().getLaxVectorConversions()) {
7783 case LangOptions::LaxVectorConversionKind::None:
7784 return false;
7786 case LangOptions::LaxVectorConversionKind::Integer:
7787 if (!srcTy->isIntegralOrEnumerationType()) {
7788 auto *Vec = srcTy->getAs<VectorType>();
7789 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7790 return false;
7792 if (!destTy->isIntegralOrEnumerationType()) {
7793 auto *Vec = destTy->getAs<VectorType>();
7794 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7795 return false;
7797 // OK, integer (vector) -> integer (vector) bitcast.
7798 break;
7800 case LangOptions::LaxVectorConversionKind::All:
7801 break;
7804 return areLaxCompatibleVectorTypes(srcTy, destTy);
7807 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7808 CastKind &Kind) {
7809 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7810 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7811 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7812 << DestTy << SrcTy << R;
7814 } else if (SrcTy->isMatrixType()) {
7815 return Diag(R.getBegin(),
7816 diag::err_invalid_conversion_between_matrix_and_type)
7817 << SrcTy << DestTy << R;
7818 } else if (DestTy->isMatrixType()) {
7819 return Diag(R.getBegin(),
7820 diag::err_invalid_conversion_between_matrix_and_type)
7821 << DestTy << SrcTy << R;
7824 Kind = CK_MatrixCast;
7825 return false;
7828 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7829 CastKind &Kind) {
7830 assert(VectorTy->isVectorType() && "Not a vector type!");
7832 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7833 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7834 return Diag(R.getBegin(),
7835 Ty->isVectorType() ?
7836 diag::err_invalid_conversion_between_vectors :
7837 diag::err_invalid_conversion_between_vector_and_integer)
7838 << VectorTy << Ty << R;
7839 } else
7840 return Diag(R.getBegin(),
7841 diag::err_invalid_conversion_between_vector_and_scalar)
7842 << VectorTy << Ty << R;
7844 Kind = CK_BitCast;
7845 return false;
7848 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7849 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7851 if (DestElemTy == SplattedExpr->getType())
7852 return SplattedExpr;
7854 assert(DestElemTy->isFloatingType() ||
7855 DestElemTy->isIntegralOrEnumerationType());
7857 CastKind CK;
7858 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7859 // OpenCL requires that we convert `true` boolean expressions to -1, but
7860 // only when splatting vectors.
7861 if (DestElemTy->isFloatingType()) {
7862 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7863 // in two steps: boolean to signed integral, then to floating.
7864 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7865 CK_BooleanToSignedIntegral);
7866 SplattedExpr = CastExprRes.get();
7867 CK = CK_IntegralToFloating;
7868 } else {
7869 CK = CK_BooleanToSignedIntegral;
7871 } else {
7872 ExprResult CastExprRes = SplattedExpr;
7873 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7874 if (CastExprRes.isInvalid())
7875 return ExprError();
7876 SplattedExpr = CastExprRes.get();
7878 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7881 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7882 Expr *CastExpr, CastKind &Kind) {
7883 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7885 QualType SrcTy = CastExpr->getType();
7887 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7888 // an ExtVectorType.
7889 // In OpenCL, casts between vectors of different types are not allowed.
7890 // (See OpenCL 6.2).
7891 if (SrcTy->isVectorType()) {
7892 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7893 (getLangOpts().OpenCL &&
7894 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7895 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7896 << DestTy << SrcTy << R;
7897 return ExprError();
7899 Kind = CK_BitCast;
7900 return CastExpr;
7903 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7904 // conversion will take place first from scalar to elt type, and then
7905 // splat from elt type to vector.
7906 if (SrcTy->isPointerType())
7907 return Diag(R.getBegin(),
7908 diag::err_invalid_conversion_between_vector_and_scalar)
7909 << DestTy << SrcTy << R;
7911 Kind = CK_VectorSplat;
7912 return prepareVectorSplat(DestTy, CastExpr);
7915 ExprResult
7916 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7917 Declarator &D, ParsedType &Ty,
7918 SourceLocation RParenLoc, Expr *CastExpr) {
7919 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7920 "ActOnCastExpr(): missing type or expr");
7922 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7923 if (D.isInvalidType())
7924 return ExprError();
7926 if (getLangOpts().CPlusPlus) {
7927 // Check that there are no default arguments (C++ only).
7928 CheckExtraCXXDefaultArguments(D);
7929 } else {
7930 // Make sure any TypoExprs have been dealt with.
7931 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7932 if (!Res.isUsable())
7933 return ExprError();
7934 CastExpr = Res.get();
7937 checkUnusedDeclAttributes(D);
7939 QualType castType = castTInfo->getType();
7940 Ty = CreateParsedType(castType, castTInfo);
7942 bool isVectorLiteral = false;
7944 // Check for an altivec or OpenCL literal,
7945 // i.e. all the elements are integer constants.
7946 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7947 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7948 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7949 && castType->isVectorType() && (PE || PLE)) {
7950 if (PLE && PLE->getNumExprs() == 0) {
7951 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7952 return ExprError();
7954 if (PE || PLE->getNumExprs() == 1) {
7955 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7956 if (!E->isTypeDependent() && !E->getType()->isVectorType())
7957 isVectorLiteral = true;
7959 else
7960 isVectorLiteral = true;
7963 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7964 // then handle it as such.
7965 if (isVectorLiteral)
7966 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7968 // If the Expr being casted is a ParenListExpr, handle it specially.
7969 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7970 // sequence of BinOp comma operators.
7971 if (isa<ParenListExpr>(CastExpr)) {
7972 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7973 if (Result.isInvalid()) return ExprError();
7974 CastExpr = Result.get();
7977 if (getLangOpts().CPlusPlus && !castType->isVoidType())
7978 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7980 CheckTollFreeBridgeCast(castType, CastExpr);
7982 CheckObjCBridgeRelatedCast(castType, CastExpr);
7984 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7986 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7989 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7990 SourceLocation RParenLoc, Expr *E,
7991 TypeSourceInfo *TInfo) {
7992 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7993 "Expected paren or paren list expression");
7995 Expr **exprs;
7996 unsigned numExprs;
7997 Expr *subExpr;
7998 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7999 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
8000 LiteralLParenLoc = PE->getLParenLoc();
8001 LiteralRParenLoc = PE->getRParenLoc();
8002 exprs = PE->getExprs();
8003 numExprs = PE->getNumExprs();
8004 } else { // isa<ParenExpr> by assertion at function entrance
8005 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
8006 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
8007 subExpr = cast<ParenExpr>(E)->getSubExpr();
8008 exprs = &subExpr;
8009 numExprs = 1;
8012 QualType Ty = TInfo->getType();
8013 assert(Ty->isVectorType() && "Expected vector type");
8015 SmallVector<Expr *, 8> initExprs;
8016 const VectorType *VTy = Ty->castAs<VectorType>();
8017 unsigned numElems = VTy->getNumElements();
8019 // '(...)' form of vector initialization in AltiVec: the number of
8020 // initializers must be one or must match the size of the vector.
8021 // If a single value is specified in the initializer then it will be
8022 // replicated to all the components of the vector
8023 if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
8024 VTy->getElementType()))
8025 return ExprError();
8026 if (ShouldSplatAltivecScalarInCast(VTy)) {
8027 // The number of initializers must be one or must match the size of the
8028 // vector. If a single value is specified in the initializer then it will
8029 // be replicated to all the components of the vector
8030 if (numExprs == 1) {
8031 QualType ElemTy = VTy->getElementType();
8032 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8033 if (Literal.isInvalid())
8034 return ExprError();
8035 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8036 PrepareScalarCast(Literal, ElemTy));
8037 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8039 else if (numExprs < numElems) {
8040 Diag(E->getExprLoc(),
8041 diag::err_incorrect_number_of_vector_initializers);
8042 return ExprError();
8044 else
8045 initExprs.append(exprs, exprs + numExprs);
8047 else {
8048 // For OpenCL, when the number of initializers is a single value,
8049 // it will be replicated to all components of the vector.
8050 if (getLangOpts().OpenCL &&
8051 VTy->getVectorKind() == VectorType::GenericVector &&
8052 numExprs == 1) {
8053 QualType ElemTy = VTy->getElementType();
8054 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8055 if (Literal.isInvalid())
8056 return ExprError();
8057 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8058 PrepareScalarCast(Literal, ElemTy));
8059 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8062 initExprs.append(exprs, exprs + numExprs);
8064 // FIXME: This means that pretty-printing the final AST will produce curly
8065 // braces instead of the original commas.
8066 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8067 initExprs, LiteralRParenLoc);
8068 initE->setType(Ty);
8069 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8072 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
8073 /// the ParenListExpr into a sequence of comma binary operators.
8074 ExprResult
8075 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8076 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8077 if (!E)
8078 return OrigExpr;
8080 ExprResult Result(E->getExpr(0));
8082 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8083 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8084 E->getExpr(i));
8086 if (Result.isInvalid()) return ExprError();
8088 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8091 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8092 SourceLocation R,
8093 MultiExprArg Val) {
8094 return ParenListExpr::Create(Context, L, Val, R);
8097 /// Emit a specialized diagnostic when one expression is a null pointer
8098 /// constant and the other is not a pointer. Returns true if a diagnostic is
8099 /// emitted.
8100 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
8101 SourceLocation QuestionLoc) {
8102 Expr *NullExpr = LHSExpr;
8103 Expr *NonPointerExpr = RHSExpr;
8104 Expr::NullPointerConstantKind NullKind =
8105 NullExpr->isNullPointerConstant(Context,
8106 Expr::NPC_ValueDependentIsNotNull);
8108 if (NullKind == Expr::NPCK_NotNull) {
8109 NullExpr = RHSExpr;
8110 NonPointerExpr = LHSExpr;
8111 NullKind =
8112 NullExpr->isNullPointerConstant(Context,
8113 Expr::NPC_ValueDependentIsNotNull);
8116 if (NullKind == Expr::NPCK_NotNull)
8117 return false;
8119 if (NullKind == Expr::NPCK_ZeroExpression)
8120 return false;
8122 if (NullKind == Expr::NPCK_ZeroLiteral) {
8123 // In this case, check to make sure that we got here from a "NULL"
8124 // string in the source code.
8125 NullExpr = NullExpr->IgnoreParenImpCasts();
8126 SourceLocation loc = NullExpr->getExprLoc();
8127 if (!findMacroSpelling(loc, "NULL"))
8128 return false;
8131 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8132 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8133 << NonPointerExpr->getType() << DiagType
8134 << NonPointerExpr->getSourceRange();
8135 return true;
8138 /// Return false if the condition expression is valid, true otherwise.
8139 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
8140 QualType CondTy = Cond->getType();
8142 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8143 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8144 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8145 << CondTy << Cond->getSourceRange();
8146 return true;
8149 // C99 6.5.15p2
8150 if (CondTy->isScalarType()) return false;
8152 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8153 << CondTy << Cond->getSourceRange();
8154 return true;
8157 /// Return false if the NullExpr can be promoted to PointerTy,
8158 /// true otherwise.
8159 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8160 QualType PointerTy) {
8161 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8162 !NullExpr.get()->isNullPointerConstant(S.Context,
8163 Expr::NPC_ValueDependentIsNull))
8164 return true;
8166 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8167 return false;
8170 /// Checks compatibility between two pointers and return the resulting
8171 /// type.
8172 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8173 ExprResult &RHS,
8174 SourceLocation Loc) {
8175 QualType LHSTy = LHS.get()->getType();
8176 QualType RHSTy = RHS.get()->getType();
8178 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8179 // Two identical pointers types are always compatible.
8180 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8183 QualType lhptee, rhptee;
8185 // Get the pointee types.
8186 bool IsBlockPointer = false;
8187 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8188 lhptee = LHSBTy->getPointeeType();
8189 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8190 IsBlockPointer = true;
8191 } else {
8192 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8193 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8196 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8197 // differently qualified versions of compatible types, the result type is
8198 // a pointer to an appropriately qualified version of the composite
8199 // type.
8201 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8202 // clause doesn't make sense for our extensions. E.g. address space 2 should
8203 // be incompatible with address space 3: they may live on different devices or
8204 // anything.
8205 Qualifiers lhQual = lhptee.getQualifiers();
8206 Qualifiers rhQual = rhptee.getQualifiers();
8208 LangAS ResultAddrSpace = LangAS::Default;
8209 LangAS LAddrSpace = lhQual.getAddressSpace();
8210 LangAS RAddrSpace = rhQual.getAddressSpace();
8212 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8213 // spaces is disallowed.
8214 if (lhQual.isAddressSpaceSupersetOf(rhQual))
8215 ResultAddrSpace = LAddrSpace;
8216 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
8217 ResultAddrSpace = RAddrSpace;
8218 else {
8219 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8220 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8221 << RHS.get()->getSourceRange();
8222 return QualType();
8225 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8226 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8227 lhQual.removeCVRQualifiers();
8228 rhQual.removeCVRQualifiers();
8230 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8231 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8232 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8233 // qual types are compatible iff
8234 // * corresponded types are compatible
8235 // * CVR qualifiers are equal
8236 // * address spaces are equal
8237 // Thus for conditional operator we merge CVR and address space unqualified
8238 // pointees and if there is a composite type we return a pointer to it with
8239 // merged qualifiers.
8240 LHSCastKind =
8241 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8242 RHSCastKind =
8243 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8244 lhQual.removeAddressSpace();
8245 rhQual.removeAddressSpace();
8247 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8248 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8250 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
8252 if (CompositeTy.isNull()) {
8253 // In this situation, we assume void* type. No especially good
8254 // reason, but this is what gcc does, and we do have to pick
8255 // to get a consistent AST.
8256 QualType incompatTy;
8257 incompatTy = S.Context.getPointerType(
8258 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8259 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8260 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8262 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8263 // for casts between types with incompatible address space qualifiers.
8264 // For the following code the compiler produces casts between global and
8265 // local address spaces of the corresponded innermost pointees:
8266 // local int *global *a;
8267 // global int *global *b;
8268 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8269 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8270 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8271 << RHS.get()->getSourceRange();
8273 return incompatTy;
8276 // The pointer types are compatible.
8277 // In case of OpenCL ResultTy should have the address space qualifier
8278 // which is a superset of address spaces of both the 2nd and the 3rd
8279 // operands of the conditional operator.
8280 QualType ResultTy = [&, ResultAddrSpace]() {
8281 if (S.getLangOpts().OpenCL) {
8282 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8283 CompositeQuals.setAddressSpace(ResultAddrSpace);
8284 return S.Context
8285 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8286 .withCVRQualifiers(MergedCVRQual);
8288 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8289 }();
8290 if (IsBlockPointer)
8291 ResultTy = S.Context.getBlockPointerType(ResultTy);
8292 else
8293 ResultTy = S.Context.getPointerType(ResultTy);
8295 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8296 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8297 return ResultTy;
8300 /// Return the resulting type when the operands are both block pointers.
8301 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8302 ExprResult &LHS,
8303 ExprResult &RHS,
8304 SourceLocation Loc) {
8305 QualType LHSTy = LHS.get()->getType();
8306 QualType RHSTy = RHS.get()->getType();
8308 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8309 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8310 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8311 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8312 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8313 return destType;
8315 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8316 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8317 << RHS.get()->getSourceRange();
8318 return QualType();
8321 // We have 2 block pointer types.
8322 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8325 /// Return the resulting type when the operands are both pointers.
8326 static QualType
8327 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8328 ExprResult &RHS,
8329 SourceLocation Loc) {
8330 // get the pointer types
8331 QualType LHSTy = LHS.get()->getType();
8332 QualType RHSTy = RHS.get()->getType();
8334 // get the "pointed to" types
8335 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8336 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8338 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8339 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8340 // Figure out necessary qualifiers (C99 6.5.15p6)
8341 QualType destPointee
8342 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8343 QualType destType = S.Context.getPointerType(destPointee);
8344 // Add qualifiers if necessary.
8345 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8346 // Promote to void*.
8347 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8348 return destType;
8350 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8351 QualType destPointee
8352 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8353 QualType destType = S.Context.getPointerType(destPointee);
8354 // Add qualifiers if necessary.
8355 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8356 // Promote to void*.
8357 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8358 return destType;
8361 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8364 /// Return false if the first expression is not an integer and the second
8365 /// expression is not a pointer, true otherwise.
8366 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8367 Expr* PointerExpr, SourceLocation Loc,
8368 bool IsIntFirstExpr) {
8369 if (!PointerExpr->getType()->isPointerType() ||
8370 !Int.get()->getType()->isIntegerType())
8371 return false;
8373 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8374 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8376 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8377 << Expr1->getType() << Expr2->getType()
8378 << Expr1->getSourceRange() << Expr2->getSourceRange();
8379 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8380 CK_IntegralToPointer);
8381 return true;
8384 /// Simple conversion between integer and floating point types.
8386 /// Used when handling the OpenCL conditional operator where the
8387 /// condition is a vector while the other operands are scalar.
8389 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8390 /// types are either integer or floating type. Between the two
8391 /// operands, the type with the higher rank is defined as the "result
8392 /// type". The other operand needs to be promoted to the same type. No
8393 /// other type promotion is allowed. We cannot use
8394 /// UsualArithmeticConversions() for this purpose, since it always
8395 /// promotes promotable types.
8396 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8397 ExprResult &RHS,
8398 SourceLocation QuestionLoc) {
8399 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8400 if (LHS.isInvalid())
8401 return QualType();
8402 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8403 if (RHS.isInvalid())
8404 return QualType();
8406 // For conversion purposes, we ignore any qualifiers.
8407 // For example, "const float" and "float" are equivalent.
8408 QualType LHSType =
8409 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8410 QualType RHSType =
8411 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8413 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8414 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8415 << LHSType << LHS.get()->getSourceRange();
8416 return QualType();
8419 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8420 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8421 << RHSType << RHS.get()->getSourceRange();
8422 return QualType();
8425 // If both types are identical, no conversion is needed.
8426 if (LHSType == RHSType)
8427 return LHSType;
8429 // Now handle "real" floating types (i.e. float, double, long double).
8430 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8431 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8432 /*IsCompAssign = */ false);
8434 // Finally, we have two differing integer types.
8435 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8436 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8439 /// Convert scalar operands to a vector that matches the
8440 /// condition in length.
8442 /// Used when handling the OpenCL conditional operator where the
8443 /// condition is a vector while the other operands are scalar.
8445 /// We first compute the "result type" for the scalar operands
8446 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8447 /// into a vector of that type where the length matches the condition
8448 /// vector type. s6.11.6 requires that the element types of the result
8449 /// and the condition must have the same number of bits.
8450 static QualType
8451 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8452 QualType CondTy, SourceLocation QuestionLoc) {
8453 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8454 if (ResTy.isNull()) return QualType();
8456 const VectorType *CV = CondTy->getAs<VectorType>();
8457 assert(CV);
8459 // Determine the vector result type
8460 unsigned NumElements = CV->getNumElements();
8461 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8463 // Ensure that all types have the same number of bits
8464 if (S.Context.getTypeSize(CV->getElementType())
8465 != S.Context.getTypeSize(ResTy)) {
8466 // Since VectorTy is created internally, it does not pretty print
8467 // with an OpenCL name. Instead, we just print a description.
8468 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8469 SmallString<64> Str;
8470 llvm::raw_svector_ostream OS(Str);
8471 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8472 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8473 << CondTy << OS.str();
8474 return QualType();
8477 // Convert operands to the vector result type
8478 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8479 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8481 return VectorTy;
8484 /// Return false if this is a valid OpenCL condition vector
8485 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8486 SourceLocation QuestionLoc) {
8487 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8488 // integral type.
8489 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8490 assert(CondTy);
8491 QualType EleTy = CondTy->getElementType();
8492 if (EleTy->isIntegerType()) return false;
8494 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8495 << Cond->getType() << Cond->getSourceRange();
8496 return true;
8499 /// Return false if the vector condition type and the vector
8500 /// result type are compatible.
8502 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8503 /// number of elements, and their element types have the same number
8504 /// of bits.
8505 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8506 SourceLocation QuestionLoc) {
8507 const VectorType *CV = CondTy->getAs<VectorType>();
8508 const VectorType *RV = VecResTy->getAs<VectorType>();
8509 assert(CV && RV);
8511 if (CV->getNumElements() != RV->getNumElements()) {
8512 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8513 << CondTy << VecResTy;
8514 return true;
8517 QualType CVE = CV->getElementType();
8518 QualType RVE = RV->getElementType();
8520 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8521 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8522 << CondTy << VecResTy;
8523 return true;
8526 return false;
8529 /// Return the resulting type for the conditional operator in
8530 /// OpenCL (aka "ternary selection operator", OpenCL v1.1
8531 /// s6.3.i) when the condition is a vector type.
8532 static QualType
8533 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8534 ExprResult &LHS, ExprResult &RHS,
8535 SourceLocation QuestionLoc) {
8536 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8537 if (Cond.isInvalid())
8538 return QualType();
8539 QualType CondTy = Cond.get()->getType();
8541 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8542 return QualType();
8544 // If either operand is a vector then find the vector type of the
8545 // result as specified in OpenCL v1.1 s6.3.i.
8546 if (LHS.get()->getType()->isVectorType() ||
8547 RHS.get()->getType()->isVectorType()) {
8548 bool IsBoolVecLang =
8549 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8550 QualType VecResTy =
8551 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8552 /*isCompAssign*/ false,
8553 /*AllowBothBool*/ true,
8554 /*AllowBoolConversions*/ false,
8555 /*AllowBooleanOperation*/ IsBoolVecLang,
8556 /*ReportInvalid*/ true);
8557 if (VecResTy.isNull())
8558 return QualType();
8559 // The result type must match the condition type as specified in
8560 // OpenCL v1.1 s6.11.6.
8561 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8562 return QualType();
8563 return VecResTy;
8566 // Both operands are scalar.
8567 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8570 /// Return true if the Expr is block type
8571 static bool checkBlockType(Sema &S, const Expr *E) {
8572 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8573 QualType Ty = CE->getCallee()->getType();
8574 if (Ty->isBlockPointerType()) {
8575 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8576 return true;
8579 return false;
8582 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8583 /// In that case, LHS = cond.
8584 /// C99 6.5.15
8585 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8586 ExprResult &RHS, ExprValueKind &VK,
8587 ExprObjectKind &OK,
8588 SourceLocation QuestionLoc) {
8590 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8591 if (!LHSResult.isUsable()) return QualType();
8592 LHS = LHSResult;
8594 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8595 if (!RHSResult.isUsable()) return QualType();
8596 RHS = RHSResult;
8598 // C++ is sufficiently different to merit its own checker.
8599 if (getLangOpts().CPlusPlus)
8600 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8602 VK = VK_PRValue;
8603 OK = OK_Ordinary;
8605 if (Context.isDependenceAllowed() &&
8606 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8607 RHS.get()->isTypeDependent())) {
8608 assert(!getLangOpts().CPlusPlus);
8609 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8610 RHS.get()->containsErrors()) &&
8611 "should only occur in error-recovery path.");
8612 return Context.DependentTy;
8615 // The OpenCL operator with a vector condition is sufficiently
8616 // different to merit its own checker.
8617 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8618 Cond.get()->getType()->isExtVectorType())
8619 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8621 // First, check the condition.
8622 Cond = UsualUnaryConversions(Cond.get());
8623 if (Cond.isInvalid())
8624 return QualType();
8625 if (checkCondition(*this, Cond.get(), QuestionLoc))
8626 return QualType();
8628 // Now check the two expressions.
8629 if (LHS.get()->getType()->isVectorType() ||
8630 RHS.get()->getType()->isVectorType())
8631 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8632 /*AllowBothBool*/ true,
8633 /*AllowBoolConversions*/ false,
8634 /*AllowBooleanOperation*/ false,
8635 /*ReportInvalid*/ true);
8637 QualType ResTy =
8638 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8639 if (LHS.isInvalid() || RHS.isInvalid())
8640 return QualType();
8642 QualType LHSTy = LHS.get()->getType();
8643 QualType RHSTy = RHS.get()->getType();
8645 // Diagnose attempts to convert between __ibm128, __float128 and long double
8646 // where such conversions currently can't be handled.
8647 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8648 Diag(QuestionLoc,
8649 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8650 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8651 return QualType();
8654 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8655 // selection operator (?:).
8656 if (getLangOpts().OpenCL &&
8657 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8658 return QualType();
8661 // If both operands have arithmetic type, do the usual arithmetic conversions
8662 // to find a common type: C99 6.5.15p3,5.
8663 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8664 // Disallow invalid arithmetic conversions, such as those between bit-
8665 // precise integers types of different sizes, or between a bit-precise
8666 // integer and another type.
8667 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8668 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8669 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8670 << RHS.get()->getSourceRange();
8671 return QualType();
8674 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8675 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8677 return ResTy;
8680 // And if they're both bfloat (which isn't arithmetic), that's fine too.
8681 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8682 return Context.getCommonSugaredType(LHSTy, RHSTy);
8685 // If both operands are the same structure or union type, the result is that
8686 // type.
8687 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8688 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8689 if (LHSRT->getDecl() == RHSRT->getDecl())
8690 // "If both the operands have structure or union type, the result has
8691 // that type." This implies that CV qualifiers are dropped.
8692 return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(),
8693 RHSTy.getUnqualifiedType());
8694 // FIXME: Type of conditional expression must be complete in C mode.
8697 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8698 // The following || allows only one side to be void (a GCC-ism).
8699 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8700 QualType ResTy;
8701 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8702 ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
8703 } else if (RHSTy->isVoidType()) {
8704 ResTy = RHSTy;
8705 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8706 << RHS.get()->getSourceRange();
8707 } else {
8708 ResTy = LHSTy;
8709 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8710 << LHS.get()->getSourceRange();
8712 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
8713 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
8714 return ResTy;
8717 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8718 // the type of the other operand."
8719 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8720 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8722 // All objective-c pointer type analysis is done here.
8723 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8724 QuestionLoc);
8725 if (LHS.isInvalid() || RHS.isInvalid())
8726 return QualType();
8727 if (!compositeType.isNull())
8728 return compositeType;
8731 // Handle block pointer types.
8732 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8733 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8734 QuestionLoc);
8736 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8737 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8738 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8739 QuestionLoc);
8741 // GCC compatibility: soften pointer/integer mismatch. Note that
8742 // null pointers have been filtered out by this point.
8743 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8744 /*IsIntFirstExpr=*/true))
8745 return RHSTy;
8746 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8747 /*IsIntFirstExpr=*/false))
8748 return LHSTy;
8750 // Allow ?: operations in which both operands have the same
8751 // built-in sizeless type.
8752 if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
8753 return Context.getCommonSugaredType(LHSTy, RHSTy);
8755 // Emit a better diagnostic if one of the expressions is a null pointer
8756 // constant and the other is not a pointer type. In this case, the user most
8757 // likely forgot to take the address of the other expression.
8758 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8759 return QualType();
8761 // Otherwise, the operands are not compatible.
8762 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8763 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8764 << RHS.get()->getSourceRange();
8765 return QualType();
8768 /// FindCompositeObjCPointerType - Helper method to find composite type of
8769 /// two objective-c pointer types of the two input expressions.
8770 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8771 SourceLocation QuestionLoc) {
8772 QualType LHSTy = LHS.get()->getType();
8773 QualType RHSTy = RHS.get()->getType();
8775 // Handle things like Class and struct objc_class*. Here we case the result
8776 // to the pseudo-builtin, because that will be implicitly cast back to the
8777 // redefinition type if an attempt is made to access its fields.
8778 if (LHSTy->isObjCClassType() &&
8779 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8780 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8781 return LHSTy;
8783 if (RHSTy->isObjCClassType() &&
8784 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8785 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8786 return RHSTy;
8788 // And the same for struct objc_object* / id
8789 if (LHSTy->isObjCIdType() &&
8790 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8791 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8792 return LHSTy;
8794 if (RHSTy->isObjCIdType() &&
8795 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8796 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8797 return RHSTy;
8799 // And the same for struct objc_selector* / SEL
8800 if (Context.isObjCSelType(LHSTy) &&
8801 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8802 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8803 return LHSTy;
8805 if (Context.isObjCSelType(RHSTy) &&
8806 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8807 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8808 return RHSTy;
8810 // Check constraints for Objective-C object pointers types.
8811 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8813 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8814 // Two identical object pointer types are always compatible.
8815 return LHSTy;
8817 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8818 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8819 QualType compositeType = LHSTy;
8821 // If both operands are interfaces and either operand can be
8822 // assigned to the other, use that type as the composite
8823 // type. This allows
8824 // xxx ? (A*) a : (B*) b
8825 // where B is a subclass of A.
8827 // Additionally, as for assignment, if either type is 'id'
8828 // allow silent coercion. Finally, if the types are
8829 // incompatible then make sure to use 'id' as the composite
8830 // type so the result is acceptable for sending messages to.
8832 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8833 // It could return the composite type.
8834 if (!(compositeType =
8835 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8836 // Nothing more to do.
8837 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8838 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8839 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8840 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8841 } else if ((LHSOPT->isObjCQualifiedIdType() ||
8842 RHSOPT->isObjCQualifiedIdType()) &&
8843 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8844 true)) {
8845 // Need to handle "id<xx>" explicitly.
8846 // GCC allows qualified id and any Objective-C type to devolve to
8847 // id. Currently localizing to here until clear this should be
8848 // part of ObjCQualifiedIdTypesAreCompatible.
8849 compositeType = Context.getObjCIdType();
8850 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8851 compositeType = Context.getObjCIdType();
8852 } else {
8853 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8854 << LHSTy << RHSTy
8855 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8856 QualType incompatTy = Context.getObjCIdType();
8857 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8858 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8859 return incompatTy;
8861 // The object pointer types are compatible.
8862 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8863 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8864 return compositeType;
8866 // Check Objective-C object pointer types and 'void *'
8867 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8868 if (getLangOpts().ObjCAutoRefCount) {
8869 // ARC forbids the implicit conversion of object pointers to 'void *',
8870 // so these types are not compatible.
8871 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8872 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8873 LHS = RHS = true;
8874 return QualType();
8876 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8877 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8878 QualType destPointee
8879 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8880 QualType destType = Context.getPointerType(destPointee);
8881 // Add qualifiers if necessary.
8882 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8883 // Promote to void*.
8884 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8885 return destType;
8887 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8888 if (getLangOpts().ObjCAutoRefCount) {
8889 // ARC forbids the implicit conversion of object pointers to 'void *',
8890 // so these types are not compatible.
8891 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8892 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8893 LHS = RHS = true;
8894 return QualType();
8896 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8897 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8898 QualType destPointee
8899 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8900 QualType destType = Context.getPointerType(destPointee);
8901 // Add qualifiers if necessary.
8902 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8903 // Promote to void*.
8904 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8905 return destType;
8907 return QualType();
8910 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8911 /// ParenRange in parentheses.
8912 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8913 const PartialDiagnostic &Note,
8914 SourceRange ParenRange) {
8915 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8916 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8917 EndLoc.isValid()) {
8918 Self.Diag(Loc, Note)
8919 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8920 << FixItHint::CreateInsertion(EndLoc, ")");
8921 } else {
8922 // We can't display the parentheses, so just show the bare note.
8923 Self.Diag(Loc, Note) << ParenRange;
8927 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8928 return BinaryOperator::isAdditiveOp(Opc) ||
8929 BinaryOperator::isMultiplicativeOp(Opc) ||
8930 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8931 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8932 // not any of the logical operators. Bitwise-xor is commonly used as a
8933 // logical-xor because there is no logical-xor operator. The logical
8934 // operators, including uses of xor, have a high false positive rate for
8935 // precedence warnings.
8938 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8939 /// expression, either using a built-in or overloaded operator,
8940 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8941 /// expression.
8942 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8943 Expr **RHSExprs) {
8944 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8945 E = E->IgnoreImpCasts();
8946 E = E->IgnoreConversionOperatorSingleStep();
8947 E = E->IgnoreImpCasts();
8948 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8949 E = MTE->getSubExpr();
8950 E = E->IgnoreImpCasts();
8953 // Built-in binary operator.
8954 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8955 if (IsArithmeticOp(OP->getOpcode())) {
8956 *Opcode = OP->getOpcode();
8957 *RHSExprs = OP->getRHS();
8958 return true;
8962 // Overloaded operator.
8963 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8964 if (Call->getNumArgs() != 2)
8965 return false;
8967 // Make sure this is really a binary operator that is safe to pass into
8968 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8969 OverloadedOperatorKind OO = Call->getOperator();
8970 if (OO < OO_Plus || OO > OO_Arrow ||
8971 OO == OO_PlusPlus || OO == OO_MinusMinus)
8972 return false;
8974 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8975 if (IsArithmeticOp(OpKind)) {
8976 *Opcode = OpKind;
8977 *RHSExprs = Call->getArg(1);
8978 return true;
8982 return false;
8985 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8986 /// or is a logical expression such as (x==y) which has int type, but is
8987 /// commonly interpreted as boolean.
8988 static bool ExprLooksBoolean(Expr *E) {
8989 E = E->IgnoreParenImpCasts();
8991 if (E->getType()->isBooleanType())
8992 return true;
8993 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8994 return OP->isComparisonOp() || OP->isLogicalOp();
8995 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8996 return OP->getOpcode() == UO_LNot;
8997 if (E->getType()->isPointerType())
8998 return true;
8999 // FIXME: What about overloaded operator calls returning "unspecified boolean
9000 // type"s (commonly pointer-to-members)?
9002 return false;
9005 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9006 /// and binary operator are mixed in a way that suggests the programmer assumed
9007 /// the conditional operator has higher precedence, for example:
9008 /// "int x = a + someBinaryCondition ? 1 : 2".
9009 static void DiagnoseConditionalPrecedence(Sema &Self,
9010 SourceLocation OpLoc,
9011 Expr *Condition,
9012 Expr *LHSExpr,
9013 Expr *RHSExpr) {
9014 BinaryOperatorKind CondOpcode;
9015 Expr *CondRHS;
9017 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
9018 return;
9019 if (!ExprLooksBoolean(CondRHS))
9020 return;
9022 // The condition is an arithmetic binary expression, with a right-
9023 // hand side that looks boolean, so warn.
9025 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
9026 ? diag::warn_precedence_bitwise_conditional
9027 : diag::warn_precedence_conditional;
9029 Self.Diag(OpLoc, DiagID)
9030 << Condition->getSourceRange()
9031 << BinaryOperator::getOpcodeStr(CondOpcode);
9033 SuggestParentheses(
9034 Self, OpLoc,
9035 Self.PDiag(diag::note_precedence_silence)
9036 << BinaryOperator::getOpcodeStr(CondOpcode),
9037 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9039 SuggestParentheses(Self, OpLoc,
9040 Self.PDiag(diag::note_precedence_conditional_first),
9041 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9044 /// Compute the nullability of a conditional expression.
9045 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
9046 QualType LHSTy, QualType RHSTy,
9047 ASTContext &Ctx) {
9048 if (!ResTy->isAnyPointerType())
9049 return ResTy;
9051 auto GetNullability = [&Ctx](QualType Ty) {
9052 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
9053 if (Kind) {
9054 // For our purposes, treat _Nullable_result as _Nullable.
9055 if (*Kind == NullabilityKind::NullableResult)
9056 return NullabilityKind::Nullable;
9057 return *Kind;
9059 return NullabilityKind::Unspecified;
9062 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9063 NullabilityKind MergedKind;
9065 // Compute nullability of a binary conditional expression.
9066 if (IsBin) {
9067 if (LHSKind == NullabilityKind::NonNull)
9068 MergedKind = NullabilityKind::NonNull;
9069 else
9070 MergedKind = RHSKind;
9071 // Compute nullability of a normal conditional expression.
9072 } else {
9073 if (LHSKind == NullabilityKind::Nullable ||
9074 RHSKind == NullabilityKind::Nullable)
9075 MergedKind = NullabilityKind::Nullable;
9076 else if (LHSKind == NullabilityKind::NonNull)
9077 MergedKind = RHSKind;
9078 else if (RHSKind == NullabilityKind::NonNull)
9079 MergedKind = LHSKind;
9080 else
9081 MergedKind = NullabilityKind::Unspecified;
9084 // Return if ResTy already has the correct nullability.
9085 if (GetNullability(ResTy) == MergedKind)
9086 return ResTy;
9088 // Strip all nullability from ResTy.
9089 while (ResTy->getNullability(Ctx))
9090 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9092 // Create a new AttributedType with the new nullability kind.
9093 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
9094 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
9097 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
9098 /// in the case of a the GNU conditional expr extension.
9099 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9100 SourceLocation ColonLoc,
9101 Expr *CondExpr, Expr *LHSExpr,
9102 Expr *RHSExpr) {
9103 if (!Context.isDependenceAllowed()) {
9104 // C cannot handle TypoExpr nodes in the condition because it
9105 // doesn't handle dependent types properly, so make sure any TypoExprs have
9106 // been dealt with before checking the operands.
9107 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
9108 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
9109 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
9111 if (!CondResult.isUsable())
9112 return ExprError();
9114 if (LHSExpr) {
9115 if (!LHSResult.isUsable())
9116 return ExprError();
9119 if (!RHSResult.isUsable())
9120 return ExprError();
9122 CondExpr = CondResult.get();
9123 LHSExpr = LHSResult.get();
9124 RHSExpr = RHSResult.get();
9127 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9128 // was the condition.
9129 OpaqueValueExpr *opaqueValue = nullptr;
9130 Expr *commonExpr = nullptr;
9131 if (!LHSExpr) {
9132 commonExpr = CondExpr;
9133 // Lower out placeholder types first. This is important so that we don't
9134 // try to capture a placeholder. This happens in few cases in C++; such
9135 // as Objective-C++'s dictionary subscripting syntax.
9136 if (commonExpr->hasPlaceholderType()) {
9137 ExprResult result = CheckPlaceholderExpr(commonExpr);
9138 if (!result.isUsable()) return ExprError();
9139 commonExpr = result.get();
9141 // We usually want to apply unary conversions *before* saving, except
9142 // in the special case of a C++ l-value conditional.
9143 if (!(getLangOpts().CPlusPlus
9144 && !commonExpr->isTypeDependent()
9145 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9146 && commonExpr->isGLValue()
9147 && commonExpr->isOrdinaryOrBitFieldObject()
9148 && RHSExpr->isOrdinaryOrBitFieldObject()
9149 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9150 ExprResult commonRes = UsualUnaryConversions(commonExpr);
9151 if (commonRes.isInvalid())
9152 return ExprError();
9153 commonExpr = commonRes.get();
9156 // If the common expression is a class or array prvalue, materialize it
9157 // so that we can safely refer to it multiple times.
9158 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9159 commonExpr->getType()->isArrayType())) {
9160 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9161 if (MatExpr.isInvalid())
9162 return ExprError();
9163 commonExpr = MatExpr.get();
9166 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9167 commonExpr->getType(),
9168 commonExpr->getValueKind(),
9169 commonExpr->getObjectKind(),
9170 commonExpr);
9171 LHSExpr = CondExpr = opaqueValue;
9174 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9175 ExprValueKind VK = VK_PRValue;
9176 ExprObjectKind OK = OK_Ordinary;
9177 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9178 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9179 VK, OK, QuestionLoc);
9180 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9181 RHS.isInvalid())
9182 return ExprError();
9184 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9185 RHS.get());
9187 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9189 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9190 Context);
9192 if (!commonExpr)
9193 return new (Context)
9194 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9195 RHS.get(), result, VK, OK);
9197 return new (Context) BinaryConditionalOperator(
9198 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9199 ColonLoc, result, VK, OK);
9202 // Check if we have a conversion between incompatible cmse function pointer
9203 // types, that is, a conversion between a function pointer with the
9204 // cmse_nonsecure_call attribute and one without.
9205 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
9206 QualType ToType) {
9207 if (const auto *ToFn =
9208 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
9209 if (const auto *FromFn =
9210 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
9211 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9212 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9214 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9217 return false;
9220 // checkPointerTypesForAssignment - This is a very tricky routine (despite
9221 // being closely modeled after the C99 spec:-). The odd characteristic of this
9222 // routine is it effectively iqnores the qualifiers on the top level pointee.
9223 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9224 // FIXME: add a couple examples in this comment.
9225 static Sema::AssignConvertType
9226 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
9227 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9228 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9230 // get the "pointed to" type (ignoring qualifiers at the top level)
9231 const Type *lhptee, *rhptee;
9232 Qualifiers lhq, rhq;
9233 std::tie(lhptee, lhq) =
9234 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9235 std::tie(rhptee, rhq) =
9236 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9238 Sema::AssignConvertType ConvTy = Sema::Compatible;
9240 // C99 6.5.16.1p1: This following citation is common to constraints
9241 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9242 // qualifiers of the type *pointed to* by the right;
9244 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9245 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9246 lhq.compatiblyIncludesObjCLifetime(rhq)) {
9247 // Ignore lifetime for further calculation.
9248 lhq.removeObjCLifetime();
9249 rhq.removeObjCLifetime();
9252 if (!lhq.compatiblyIncludes(rhq)) {
9253 // Treat address-space mismatches as fatal.
9254 if (!lhq.isAddressSpaceSupersetOf(rhq))
9255 return Sema::IncompatiblePointerDiscardsQualifiers;
9257 // It's okay to add or remove GC or lifetime qualifiers when converting to
9258 // and from void*.
9259 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
9260 .compatiblyIncludes(
9261 rhq.withoutObjCGCAttr().withoutObjCLifetime())
9262 && (lhptee->isVoidType() || rhptee->isVoidType()))
9263 ; // keep old
9265 // Treat lifetime mismatches as fatal.
9266 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9267 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
9269 // For GCC/MS compatibility, other qualifier mismatches are treated
9270 // as still compatible in C.
9271 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9274 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9275 // incomplete type and the other is a pointer to a qualified or unqualified
9276 // version of void...
9277 if (lhptee->isVoidType()) {
9278 if (rhptee->isIncompleteOrObjectType())
9279 return ConvTy;
9281 // As an extension, we allow cast to/from void* to function pointer.
9282 assert(rhptee->isFunctionType());
9283 return Sema::FunctionVoidPointer;
9286 if (rhptee->isVoidType()) {
9287 if (lhptee->isIncompleteOrObjectType())
9288 return ConvTy;
9290 // As an extension, we allow cast to/from void* to function pointer.
9291 assert(lhptee->isFunctionType());
9292 return Sema::FunctionVoidPointer;
9295 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9296 // unqualified versions of compatible types, ...
9297 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9298 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9299 // Check if the pointee types are compatible ignoring the sign.
9300 // We explicitly check for char so that we catch "char" vs
9301 // "unsigned char" on systems where "char" is unsigned.
9302 if (lhptee->isCharType())
9303 ltrans = S.Context.UnsignedCharTy;
9304 else if (lhptee->hasSignedIntegerRepresentation())
9305 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9307 if (rhptee->isCharType())
9308 rtrans = S.Context.UnsignedCharTy;
9309 else if (rhptee->hasSignedIntegerRepresentation())
9310 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9312 if (ltrans == rtrans) {
9313 // Types are compatible ignoring the sign. Qualifier incompatibility
9314 // takes priority over sign incompatibility because the sign
9315 // warning can be disabled.
9316 if (ConvTy != Sema::Compatible)
9317 return ConvTy;
9319 return Sema::IncompatiblePointerSign;
9322 // If we are a multi-level pointer, it's possible that our issue is simply
9323 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9324 // the eventual target type is the same and the pointers have the same
9325 // level of indirection, this must be the issue.
9326 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9327 do {
9328 std::tie(lhptee, lhq) =
9329 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9330 std::tie(rhptee, rhq) =
9331 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9333 // Inconsistent address spaces at this point is invalid, even if the
9334 // address spaces would be compatible.
9335 // FIXME: This doesn't catch address space mismatches for pointers of
9336 // different nesting levels, like:
9337 // __local int *** a;
9338 // int ** b = a;
9339 // It's not clear how to actually determine when such pointers are
9340 // invalidly incompatible.
9341 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9342 return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
9344 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9346 if (lhptee == rhptee)
9347 return Sema::IncompatibleNestedPointerQualifiers;
9350 // General pointer incompatibility takes priority over qualifiers.
9351 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9352 return Sema::IncompatibleFunctionPointer;
9353 return Sema::IncompatiblePointer;
9355 if (!S.getLangOpts().CPlusPlus &&
9356 S.IsFunctionConversion(ltrans, rtrans, ltrans))
9357 return Sema::IncompatibleFunctionPointer;
9358 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9359 return Sema::IncompatibleFunctionPointer;
9360 return ConvTy;
9363 /// checkBlockPointerTypesForAssignment - This routine determines whether two
9364 /// block pointer types are compatible or whether a block and normal pointer
9365 /// are compatible. It is more restrict than comparing two function pointer
9366 // types.
9367 static Sema::AssignConvertType
9368 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
9369 QualType RHSType) {
9370 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9371 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9373 QualType lhptee, rhptee;
9375 // get the "pointed to" type (ignoring qualifiers at the top level)
9376 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9377 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9379 // In C++, the types have to match exactly.
9380 if (S.getLangOpts().CPlusPlus)
9381 return Sema::IncompatibleBlockPointer;
9383 Sema::AssignConvertType ConvTy = Sema::Compatible;
9385 // For blocks we enforce that qualifiers are identical.
9386 Qualifiers LQuals = lhptee.getLocalQualifiers();
9387 Qualifiers RQuals = rhptee.getLocalQualifiers();
9388 if (S.getLangOpts().OpenCL) {
9389 LQuals.removeAddressSpace();
9390 RQuals.removeAddressSpace();
9392 if (LQuals != RQuals)
9393 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9395 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9396 // assignment.
9397 // The current behavior is similar to C++ lambdas. A block might be
9398 // assigned to a variable iff its return type and parameters are compatible
9399 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9400 // an assignment. Presumably it should behave in way that a function pointer
9401 // assignment does in C, so for each parameter and return type:
9402 // * CVR and address space of LHS should be a superset of CVR and address
9403 // space of RHS.
9404 // * unqualified types should be compatible.
9405 if (S.getLangOpts().OpenCL) {
9406 if (!S.Context.typesAreBlockPointerCompatible(
9407 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9408 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9409 return Sema::IncompatibleBlockPointer;
9410 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9411 return Sema::IncompatibleBlockPointer;
9413 return ConvTy;
9416 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9417 /// for assignment compatibility.
9418 static Sema::AssignConvertType
9419 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
9420 QualType RHSType) {
9421 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9422 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9424 if (LHSType->isObjCBuiltinType()) {
9425 // Class is not compatible with ObjC object pointers.
9426 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9427 !RHSType->isObjCQualifiedClassType())
9428 return Sema::IncompatiblePointer;
9429 return Sema::Compatible;
9431 if (RHSType->isObjCBuiltinType()) {
9432 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9433 !LHSType->isObjCQualifiedClassType())
9434 return Sema::IncompatiblePointer;
9435 return Sema::Compatible;
9437 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9438 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9440 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9441 // make an exception for id<P>
9442 !LHSType->isObjCQualifiedIdType())
9443 return Sema::CompatiblePointerDiscardsQualifiers;
9445 if (S.Context.typesAreCompatible(LHSType, RHSType))
9446 return Sema::Compatible;
9447 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9448 return Sema::IncompatibleObjCQualifiedId;
9449 return Sema::IncompatiblePointer;
9452 Sema::AssignConvertType
9453 Sema::CheckAssignmentConstraints(SourceLocation Loc,
9454 QualType LHSType, QualType RHSType) {
9455 // Fake up an opaque expression. We don't actually care about what
9456 // cast operations are required, so if CheckAssignmentConstraints
9457 // adds casts to this they'll be wasted, but fortunately that doesn't
9458 // usually happen on valid code.
9459 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9460 ExprResult RHSPtr = &RHSExpr;
9461 CastKind K;
9463 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9466 /// This helper function returns true if QT is a vector type that has element
9467 /// type ElementType.
9468 static bool isVector(QualType QT, QualType ElementType) {
9469 if (const VectorType *VT = QT->getAs<VectorType>())
9470 return VT->getElementType().getCanonicalType() == ElementType;
9471 return false;
9474 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9475 /// has code to accommodate several GCC extensions when type checking
9476 /// pointers. Here are some objectionable examples that GCC considers warnings:
9478 /// int a, *pint;
9479 /// short *pshort;
9480 /// struct foo *pfoo;
9482 /// pint = pshort; // warning: assignment from incompatible pointer type
9483 /// a = pint; // warning: assignment makes integer from pointer without a cast
9484 /// pint = a; // warning: assignment makes pointer from integer without a cast
9485 /// pint = pfoo; // warning: assignment from incompatible pointer type
9487 /// As a result, the code for dealing with pointers is more complex than the
9488 /// C99 spec dictates.
9490 /// Sets 'Kind' for any result kind except Incompatible.
9491 Sema::AssignConvertType
9492 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9493 CastKind &Kind, bool ConvertRHS) {
9494 QualType RHSType = RHS.get()->getType();
9495 QualType OrigLHSType = LHSType;
9497 // Get canonical types. We're not formatting these types, just comparing
9498 // them.
9499 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9500 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9502 // Common case: no conversion required.
9503 if (LHSType == RHSType) {
9504 Kind = CK_NoOp;
9505 return Compatible;
9508 // If the LHS has an __auto_type, there are no additional type constraints
9509 // to be worried about.
9510 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9511 if (AT->isGNUAutoType()) {
9512 Kind = CK_NoOp;
9513 return Compatible;
9517 // If we have an atomic type, try a non-atomic assignment, then just add an
9518 // atomic qualification step.
9519 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9520 Sema::AssignConvertType result =
9521 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9522 if (result != Compatible)
9523 return result;
9524 if (Kind != CK_NoOp && ConvertRHS)
9525 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9526 Kind = CK_NonAtomicToAtomic;
9527 return Compatible;
9530 // If the left-hand side is a reference type, then we are in a
9531 // (rare!) case where we've allowed the use of references in C,
9532 // e.g., as a parameter type in a built-in function. In this case,
9533 // just make sure that the type referenced is compatible with the
9534 // right-hand side type. The caller is responsible for adjusting
9535 // LHSType so that the resulting expression does not have reference
9536 // type.
9537 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9538 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9539 Kind = CK_LValueBitCast;
9540 return Compatible;
9542 return Incompatible;
9545 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9546 // to the same ExtVector type.
9547 if (LHSType->isExtVectorType()) {
9548 if (RHSType->isExtVectorType())
9549 return Incompatible;
9550 if (RHSType->isArithmeticType()) {
9551 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9552 if (ConvertRHS)
9553 RHS = prepareVectorSplat(LHSType, RHS.get());
9554 Kind = CK_VectorSplat;
9555 return Compatible;
9559 // Conversions to or from vector type.
9560 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9561 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9562 // Allow assignments of an AltiVec vector type to an equivalent GCC
9563 // vector type and vice versa
9564 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9565 Kind = CK_BitCast;
9566 return Compatible;
9569 // If we are allowing lax vector conversions, and LHS and RHS are both
9570 // vectors, the total size only needs to be the same. This is a bitcast;
9571 // no bits are changed but the result type is different.
9572 if (isLaxVectorConversion(RHSType, LHSType)) {
9573 // The default for lax vector conversions with Altivec vectors will
9574 // change, so if we are converting between vector types where
9575 // at least one is an Altivec vector, emit a warning.
9576 if (anyAltivecTypes(RHSType, LHSType) &&
9577 !areSameVectorElemTypes(RHSType, LHSType))
9578 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9579 << RHSType << LHSType;
9580 Kind = CK_BitCast;
9581 return IncompatibleVectors;
9585 // When the RHS comes from another lax conversion (e.g. binops between
9586 // scalars and vectors) the result is canonicalized as a vector. When the
9587 // LHS is also a vector, the lax is allowed by the condition above. Handle
9588 // the case where LHS is a scalar.
9589 if (LHSType->isScalarType()) {
9590 const VectorType *VecType = RHSType->getAs<VectorType>();
9591 if (VecType && VecType->getNumElements() == 1 &&
9592 isLaxVectorConversion(RHSType, LHSType)) {
9593 if (VecType->getVectorKind() == VectorType::AltiVecVector)
9594 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9595 << RHSType << LHSType;
9596 ExprResult *VecExpr = &RHS;
9597 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9598 Kind = CK_BitCast;
9599 return Compatible;
9603 // Allow assignments between fixed-length and sizeless SVE vectors.
9604 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9605 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
9606 if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9607 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9608 Kind = CK_BitCast;
9609 return Compatible;
9612 return Incompatible;
9615 // Diagnose attempts to convert between __ibm128, __float128 and long double
9616 // where such conversions currently can't be handled.
9617 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9618 return Incompatible;
9620 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9621 // discards the imaginary part.
9622 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9623 !LHSType->getAs<ComplexType>())
9624 return Incompatible;
9626 // Arithmetic conversions.
9627 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9628 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9629 if (ConvertRHS)
9630 Kind = PrepareScalarCast(RHS, LHSType);
9631 return Compatible;
9634 // Conversions to normal pointers.
9635 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9636 // U* -> T*
9637 if (isa<PointerType>(RHSType)) {
9638 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9639 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9640 if (AddrSpaceL != AddrSpaceR)
9641 Kind = CK_AddressSpaceConversion;
9642 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9643 Kind = CK_NoOp;
9644 else
9645 Kind = CK_BitCast;
9646 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9649 // int -> T*
9650 if (RHSType->isIntegerType()) {
9651 Kind = CK_IntegralToPointer; // FIXME: null?
9652 return IntToPointer;
9655 // C pointers are not compatible with ObjC object pointers,
9656 // with two exceptions:
9657 if (isa<ObjCObjectPointerType>(RHSType)) {
9658 // - conversions to void*
9659 if (LHSPointer->getPointeeType()->isVoidType()) {
9660 Kind = CK_BitCast;
9661 return Compatible;
9664 // - conversions from 'Class' to the redefinition type
9665 if (RHSType->isObjCClassType() &&
9666 Context.hasSameType(LHSType,
9667 Context.getObjCClassRedefinitionType())) {
9668 Kind = CK_BitCast;
9669 return Compatible;
9672 Kind = CK_BitCast;
9673 return IncompatiblePointer;
9676 // U^ -> void*
9677 if (RHSType->getAs<BlockPointerType>()) {
9678 if (LHSPointer->getPointeeType()->isVoidType()) {
9679 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9680 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9681 ->getPointeeType()
9682 .getAddressSpace();
9683 Kind =
9684 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9685 return Compatible;
9689 return Incompatible;
9692 // Conversions to block pointers.
9693 if (isa<BlockPointerType>(LHSType)) {
9694 // U^ -> T^
9695 if (RHSType->isBlockPointerType()) {
9696 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9697 ->getPointeeType()
9698 .getAddressSpace();
9699 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9700 ->getPointeeType()
9701 .getAddressSpace();
9702 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9703 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9706 // int or null -> T^
9707 if (RHSType->isIntegerType()) {
9708 Kind = CK_IntegralToPointer; // FIXME: null
9709 return IntToBlockPointer;
9712 // id -> T^
9713 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9714 Kind = CK_AnyPointerToBlockPointerCast;
9715 return Compatible;
9718 // void* -> T^
9719 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9720 if (RHSPT->getPointeeType()->isVoidType()) {
9721 Kind = CK_AnyPointerToBlockPointerCast;
9722 return Compatible;
9725 return Incompatible;
9728 // Conversions to Objective-C pointers.
9729 if (isa<ObjCObjectPointerType>(LHSType)) {
9730 // A* -> B*
9731 if (RHSType->isObjCObjectPointerType()) {
9732 Kind = CK_BitCast;
9733 Sema::AssignConvertType result =
9734 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9735 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9736 result == Compatible &&
9737 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9738 result = IncompatibleObjCWeakRef;
9739 return result;
9742 // int or null -> A*
9743 if (RHSType->isIntegerType()) {
9744 Kind = CK_IntegralToPointer; // FIXME: null
9745 return IntToPointer;
9748 // In general, C pointers are not compatible with ObjC object pointers,
9749 // with two exceptions:
9750 if (isa<PointerType>(RHSType)) {
9751 Kind = CK_CPointerToObjCPointerCast;
9753 // - conversions from 'void*'
9754 if (RHSType->isVoidPointerType()) {
9755 return Compatible;
9758 // - conversions to 'Class' from its redefinition type
9759 if (LHSType->isObjCClassType() &&
9760 Context.hasSameType(RHSType,
9761 Context.getObjCClassRedefinitionType())) {
9762 return Compatible;
9765 return IncompatiblePointer;
9768 // Only under strict condition T^ is compatible with an Objective-C pointer.
9769 if (RHSType->isBlockPointerType() &&
9770 LHSType->isBlockCompatibleObjCPointerType(Context)) {
9771 if (ConvertRHS)
9772 maybeExtendBlockObject(RHS);
9773 Kind = CK_BlockPointerToObjCPointerCast;
9774 return Compatible;
9777 return Incompatible;
9780 // Conversions from pointers that are not covered by the above.
9781 if (isa<PointerType>(RHSType)) {
9782 // T* -> _Bool
9783 if (LHSType == Context.BoolTy) {
9784 Kind = CK_PointerToBoolean;
9785 return Compatible;
9788 // T* -> int
9789 if (LHSType->isIntegerType()) {
9790 Kind = CK_PointerToIntegral;
9791 return PointerToInt;
9794 return Incompatible;
9797 // Conversions from Objective-C pointers that are not covered by the above.
9798 if (isa<ObjCObjectPointerType>(RHSType)) {
9799 // T* -> _Bool
9800 if (LHSType == Context.BoolTy) {
9801 Kind = CK_PointerToBoolean;
9802 return Compatible;
9805 // T* -> int
9806 if (LHSType->isIntegerType()) {
9807 Kind = CK_PointerToIntegral;
9808 return PointerToInt;
9811 return Incompatible;
9814 // struct A -> struct B
9815 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9816 if (Context.typesAreCompatible(LHSType, RHSType)) {
9817 Kind = CK_NoOp;
9818 return Compatible;
9822 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9823 Kind = CK_IntToOCLSampler;
9824 return Compatible;
9827 return Incompatible;
9830 /// Constructs a transparent union from an expression that is
9831 /// used to initialize the transparent union.
9832 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9833 ExprResult &EResult, QualType UnionType,
9834 FieldDecl *Field) {
9835 // Build an initializer list that designates the appropriate member
9836 // of the transparent union.
9837 Expr *E = EResult.get();
9838 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9839 E, SourceLocation());
9840 Initializer->setType(UnionType);
9841 Initializer->setInitializedFieldInUnion(Field);
9843 // Build a compound literal constructing a value of the transparent
9844 // union type from this initializer list.
9845 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9846 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9847 VK_PRValue, Initializer, false);
9850 Sema::AssignConvertType
9851 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9852 ExprResult &RHS) {
9853 QualType RHSType = RHS.get()->getType();
9855 // If the ArgType is a Union type, we want to handle a potential
9856 // transparent_union GCC extension.
9857 const RecordType *UT = ArgType->getAsUnionType();
9858 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9859 return Incompatible;
9861 // The field to initialize within the transparent union.
9862 RecordDecl *UD = UT->getDecl();
9863 FieldDecl *InitField = nullptr;
9864 // It's compatible if the expression matches any of the fields.
9865 for (auto *it : UD->fields()) {
9866 if (it->getType()->isPointerType()) {
9867 // If the transparent union contains a pointer type, we allow:
9868 // 1) void pointer
9869 // 2) null pointer constant
9870 if (RHSType->isPointerType())
9871 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9872 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9873 InitField = it;
9874 break;
9877 if (RHS.get()->isNullPointerConstant(Context,
9878 Expr::NPC_ValueDependentIsNull)) {
9879 RHS = ImpCastExprToType(RHS.get(), it->getType(),
9880 CK_NullToPointer);
9881 InitField = it;
9882 break;
9886 CastKind Kind;
9887 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9888 == Compatible) {
9889 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9890 InitField = it;
9891 break;
9895 if (!InitField)
9896 return Incompatible;
9898 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9899 return Compatible;
9902 Sema::AssignConvertType
9903 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9904 bool Diagnose,
9905 bool DiagnoseCFAudited,
9906 bool ConvertRHS) {
9907 // We need to be able to tell the caller whether we diagnosed a problem, if
9908 // they ask us to issue diagnostics.
9909 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9911 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9912 // we can't avoid *all* modifications at the moment, so we need some somewhere
9913 // to put the updated value.
9914 ExprResult LocalRHS = CallerRHS;
9915 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9917 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9918 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9919 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9920 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9921 Diag(RHS.get()->getExprLoc(),
9922 diag::warn_noderef_to_dereferenceable_pointer)
9923 << RHS.get()->getSourceRange();
9928 if (getLangOpts().CPlusPlus) {
9929 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9930 // C++ 5.17p3: If the left operand is not of class type, the
9931 // expression is implicitly converted (C++ 4) to the
9932 // cv-unqualified type of the left operand.
9933 QualType RHSType = RHS.get()->getType();
9934 if (Diagnose) {
9935 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9936 AA_Assigning);
9937 } else {
9938 ImplicitConversionSequence ICS =
9939 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9940 /*SuppressUserConversions=*/false,
9941 AllowedExplicit::None,
9942 /*InOverloadResolution=*/false,
9943 /*CStyle=*/false,
9944 /*AllowObjCWritebackConversion=*/false);
9945 if (ICS.isFailure())
9946 return Incompatible;
9947 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9948 ICS, AA_Assigning);
9950 if (RHS.isInvalid())
9951 return Incompatible;
9952 Sema::AssignConvertType result = Compatible;
9953 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9954 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9955 result = IncompatibleObjCWeakRef;
9956 return result;
9959 // FIXME: Currently, we fall through and treat C++ classes like C
9960 // structures.
9961 // FIXME: We also fall through for atomics; not sure what should
9962 // happen there, though.
9963 } else if (RHS.get()->getType() == Context.OverloadTy) {
9964 // As a set of extensions to C, we support overloading on functions. These
9965 // functions need to be resolved here.
9966 DeclAccessPair DAP;
9967 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9968 RHS.get(), LHSType, /*Complain=*/false, DAP))
9969 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9970 else
9971 return Incompatible;
9974 // C99 6.5.16.1p1: the left operand is a pointer and the right is
9975 // a null pointer constant.
9976 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9977 LHSType->isBlockPointerType()) &&
9978 RHS.get()->isNullPointerConstant(Context,
9979 Expr::NPC_ValueDependentIsNull)) {
9980 if (Diagnose || ConvertRHS) {
9981 CastKind Kind;
9982 CXXCastPath Path;
9983 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9984 /*IgnoreBaseAccess=*/false, Diagnose);
9985 if (ConvertRHS)
9986 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9988 return Compatible;
9991 // OpenCL queue_t type assignment.
9992 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9993 Context, Expr::NPC_ValueDependentIsNull)) {
9994 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9995 return Compatible;
9998 // This check seems unnatural, however it is necessary to ensure the proper
9999 // conversion of functions/arrays. If the conversion were done for all
10000 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10001 // expressions that suppress this implicit conversion (&, sizeof).
10003 // Suppress this for references: C++ 8.5.3p5.
10004 if (!LHSType->isReferenceType()) {
10005 // FIXME: We potentially allocate here even if ConvertRHS is false.
10006 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
10007 if (RHS.isInvalid())
10008 return Incompatible;
10010 CastKind Kind;
10011 Sema::AssignConvertType result =
10012 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10014 // C99 6.5.16.1p2: The value of the right operand is converted to the
10015 // type of the assignment expression.
10016 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10017 // so that we can use references in built-in functions even in C.
10018 // The getNonReferenceType() call makes sure that the resulting expression
10019 // does not have reference type.
10020 if (result != Incompatible && RHS.get()->getType() != LHSType) {
10021 QualType Ty = LHSType.getNonLValueExprType(Context);
10022 Expr *E = RHS.get();
10024 // Check for various Objective-C errors. If we are not reporting
10025 // diagnostics and just checking for errors, e.g., during overload
10026 // resolution, return Incompatible to indicate the failure.
10027 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10028 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
10029 Diagnose, DiagnoseCFAudited) != ACR_okay) {
10030 if (!Diagnose)
10031 return Incompatible;
10033 if (getLangOpts().ObjC &&
10034 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
10035 E->getType(), E, Diagnose) ||
10036 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
10037 if (!Diagnose)
10038 return Incompatible;
10039 // Replace the expression with a corrected version and continue so we
10040 // can find further errors.
10041 RHS = E;
10042 return Compatible;
10045 if (ConvertRHS)
10046 RHS = ImpCastExprToType(E, Ty, Kind);
10049 return result;
10052 namespace {
10053 /// The original operand to an operator, prior to the application of the usual
10054 /// arithmetic conversions and converting the arguments of a builtin operator
10055 /// candidate.
10056 struct OriginalOperand {
10057 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10058 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10059 Op = MTE->getSubExpr();
10060 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10061 Op = BTE->getSubExpr();
10062 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10063 Orig = ICE->getSubExprAsWritten();
10064 Conversion = ICE->getConversionFunction();
10068 QualType getType() const { return Orig->getType(); }
10070 Expr *Orig;
10071 NamedDecl *Conversion;
10075 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10076 ExprResult &RHS) {
10077 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10079 Diag(Loc, diag::err_typecheck_invalid_operands)
10080 << OrigLHS.getType() << OrigRHS.getType()
10081 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10083 // If a user-defined conversion was applied to either of the operands prior
10084 // to applying the built-in operator rules, tell the user about it.
10085 if (OrigLHS.Conversion) {
10086 Diag(OrigLHS.Conversion->getLocation(),
10087 diag::note_typecheck_invalid_operands_converted)
10088 << 0 << LHS.get()->getType();
10090 if (OrigRHS.Conversion) {
10091 Diag(OrigRHS.Conversion->getLocation(),
10092 diag::note_typecheck_invalid_operands_converted)
10093 << 1 << RHS.get()->getType();
10096 return QualType();
10099 // Diagnose cases where a scalar was implicitly converted to a vector and
10100 // diagnose the underlying types. Otherwise, diagnose the error
10101 // as invalid vector logical operands for non-C++ cases.
10102 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10103 ExprResult &RHS) {
10104 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10105 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10107 bool LHSNatVec = LHSType->isVectorType();
10108 bool RHSNatVec = RHSType->isVectorType();
10110 if (!(LHSNatVec && RHSNatVec)) {
10111 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10112 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10113 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10114 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10115 << Vector->getSourceRange();
10116 return QualType();
10119 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10120 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10121 << RHS.get()->getSourceRange();
10123 return QualType();
10126 /// Try to convert a value of non-vector type to a vector type by converting
10127 /// the type to the element type of the vector and then performing a splat.
10128 /// If the language is OpenCL, we only use conversions that promote scalar
10129 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10130 /// for float->int.
10132 /// OpenCL V2.0 6.2.6.p2:
10133 /// An error shall occur if any scalar operand type has greater rank
10134 /// than the type of the vector element.
10136 /// \param scalar - if non-null, actually perform the conversions
10137 /// \return true if the operation fails (but without diagnosing the failure)
10138 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10139 QualType scalarTy,
10140 QualType vectorEltTy,
10141 QualType vectorTy,
10142 unsigned &DiagID) {
10143 // The conversion to apply to the scalar before splatting it,
10144 // if necessary.
10145 CastKind scalarCast = CK_NoOp;
10147 if (vectorEltTy->isIntegralType(S.Context)) {
10148 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10149 (scalarTy->isIntegerType() &&
10150 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10151 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10152 return true;
10154 if (!scalarTy->isIntegralType(S.Context))
10155 return true;
10156 scalarCast = CK_IntegralCast;
10157 } else if (vectorEltTy->isRealFloatingType()) {
10158 if (scalarTy->isRealFloatingType()) {
10159 if (S.getLangOpts().OpenCL &&
10160 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10161 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10162 return true;
10164 scalarCast = CK_FloatingCast;
10166 else if (scalarTy->isIntegralType(S.Context))
10167 scalarCast = CK_IntegralToFloating;
10168 else
10169 return true;
10170 } else {
10171 return true;
10174 // Adjust scalar if desired.
10175 if (scalar) {
10176 if (scalarCast != CK_NoOp)
10177 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10178 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10180 return false;
10183 /// Convert vector E to a vector with the same number of elements but different
10184 /// element type.
10185 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10186 const auto *VecTy = E->getType()->getAs<VectorType>();
10187 assert(VecTy && "Expression E must be a vector");
10188 QualType NewVecTy =
10189 VecTy->isExtVectorType()
10190 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10191 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10192 VecTy->getVectorKind());
10194 // Look through the implicit cast. Return the subexpression if its type is
10195 // NewVecTy.
10196 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10197 if (ICE->getSubExpr()->getType() == NewVecTy)
10198 return ICE->getSubExpr();
10200 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10201 return S.ImpCastExprToType(E, NewVecTy, Cast);
10204 /// Test if a (constant) integer Int can be casted to another integer type
10205 /// IntTy without losing precision.
10206 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10207 QualType OtherIntTy) {
10208 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10210 // Reject cases where the value of the Int is unknown as that would
10211 // possibly cause truncation, but accept cases where the scalar can be
10212 // demoted without loss of precision.
10213 Expr::EvalResult EVResult;
10214 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10215 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10216 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10217 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10219 if (CstInt) {
10220 // If the scalar is constant and is of a higher order and has more active
10221 // bits that the vector element type, reject it.
10222 llvm::APSInt Result = EVResult.Val.getInt();
10223 unsigned NumBits = IntSigned
10224 ? (Result.isNegative() ? Result.getMinSignedBits()
10225 : Result.getActiveBits())
10226 : Result.getActiveBits();
10227 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10228 return true;
10230 // If the signedness of the scalar type and the vector element type
10231 // differs and the number of bits is greater than that of the vector
10232 // element reject it.
10233 return (IntSigned != OtherIntSigned &&
10234 NumBits > S.Context.getIntWidth(OtherIntTy));
10237 // Reject cases where the value of the scalar is not constant and it's
10238 // order is greater than that of the vector element type.
10239 return (Order < 0);
10242 /// Test if a (constant) integer Int can be casted to floating point type
10243 /// FloatTy without losing precision.
10244 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10245 QualType FloatTy) {
10246 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10248 // Determine if the integer constant can be expressed as a floating point
10249 // number of the appropriate type.
10250 Expr::EvalResult EVResult;
10251 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10253 uint64_t Bits = 0;
10254 if (CstInt) {
10255 // Reject constants that would be truncated if they were converted to
10256 // the floating point type. Test by simple to/from conversion.
10257 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10258 // could be avoided if there was a convertFromAPInt method
10259 // which could signal back if implicit truncation occurred.
10260 llvm::APSInt Result = EVResult.Val.getInt();
10261 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10262 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10263 llvm::APFloat::rmTowardZero);
10264 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10265 !IntTy->hasSignedIntegerRepresentation());
10266 bool Ignored = false;
10267 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10268 &Ignored);
10269 if (Result != ConvertBack)
10270 return true;
10271 } else {
10272 // Reject types that cannot be fully encoded into the mantissa of
10273 // the float.
10274 Bits = S.Context.getTypeSize(IntTy);
10275 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10276 S.Context.getFloatTypeSemantics(FloatTy));
10277 if (Bits > FloatPrec)
10278 return true;
10281 return false;
10284 /// Attempt to convert and splat Scalar into a vector whose types matches
10285 /// Vector following GCC conversion rules. The rule is that implicit
10286 /// conversion can occur when Scalar can be casted to match Vector's element
10287 /// type without causing truncation of Scalar.
10288 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10289 ExprResult *Vector) {
10290 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10291 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10292 QualType VectorEltTy;
10294 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10295 assert(!isa<ExtVectorType>(VT) &&
10296 "ExtVectorTypes should not be handled here!");
10297 VectorEltTy = VT->getElementType();
10298 } else if (VectorTy->isVLSTBuiltinType()) {
10299 VectorEltTy =
10300 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10301 } else {
10302 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10305 // Reject cases where the vector element type or the scalar element type are
10306 // not integral or floating point types.
10307 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10308 return true;
10310 // The conversion to apply to the scalar before splatting it,
10311 // if necessary.
10312 CastKind ScalarCast = CK_NoOp;
10314 // Accept cases where the vector elements are integers and the scalar is
10315 // an integer.
10316 // FIXME: Notionally if the scalar was a floating point value with a precise
10317 // integral representation, we could cast it to an appropriate integer
10318 // type and then perform the rest of the checks here. GCC will perform
10319 // this conversion in some cases as determined by the input language.
10320 // We should accept it on a language independent basis.
10321 if (VectorEltTy->isIntegralType(S.Context) &&
10322 ScalarTy->isIntegralType(S.Context) &&
10323 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10325 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10326 return true;
10328 ScalarCast = CK_IntegralCast;
10329 } else if (VectorEltTy->isIntegralType(S.Context) &&
10330 ScalarTy->isRealFloatingType()) {
10331 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10332 ScalarCast = CK_FloatingToIntegral;
10333 else
10334 return true;
10335 } else if (VectorEltTy->isRealFloatingType()) {
10336 if (ScalarTy->isRealFloatingType()) {
10338 // Reject cases where the scalar type is not a constant and has a higher
10339 // Order than the vector element type.
10340 llvm::APFloat Result(0.0);
10342 // Determine whether this is a constant scalar. In the event that the
10343 // value is dependent (and thus cannot be evaluated by the constant
10344 // evaluator), skip the evaluation. This will then diagnose once the
10345 // expression is instantiated.
10346 bool CstScalar = Scalar->get()->isValueDependent() ||
10347 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10348 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10349 if (!CstScalar && Order < 0)
10350 return true;
10352 // If the scalar cannot be safely casted to the vector element type,
10353 // reject it.
10354 if (CstScalar) {
10355 bool Truncated = false;
10356 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10357 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10358 if (Truncated)
10359 return true;
10362 ScalarCast = CK_FloatingCast;
10363 } else if (ScalarTy->isIntegralType(S.Context)) {
10364 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10365 return true;
10367 ScalarCast = CK_IntegralToFloating;
10368 } else
10369 return true;
10370 } else if (ScalarTy->isEnumeralType())
10371 return true;
10373 // Adjust scalar if desired.
10374 if (Scalar) {
10375 if (ScalarCast != CK_NoOp)
10376 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10377 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10379 return false;
10382 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10383 SourceLocation Loc, bool IsCompAssign,
10384 bool AllowBothBool,
10385 bool AllowBoolConversions,
10386 bool AllowBoolOperation,
10387 bool ReportInvalid) {
10388 if (!IsCompAssign) {
10389 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10390 if (LHS.isInvalid())
10391 return QualType();
10393 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10394 if (RHS.isInvalid())
10395 return QualType();
10397 // For conversion purposes, we ignore any qualifiers.
10398 // For example, "const float" and "float" are equivalent.
10399 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10400 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10402 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10403 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10404 assert(LHSVecType || RHSVecType);
10406 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
10407 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
10408 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10410 // AltiVec-style "vector bool op vector bool" combinations are allowed
10411 // for some operators but not others.
10412 if (!AllowBothBool &&
10413 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10414 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10415 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10417 // This operation may not be performed on boolean vectors.
10418 if (!AllowBoolOperation &&
10419 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10420 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10422 // If the vector types are identical, return.
10423 if (Context.hasSameType(LHSType, RHSType))
10424 return Context.getCommonSugaredType(LHSType, RHSType);
10426 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10427 if (LHSVecType && RHSVecType &&
10428 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10429 if (isa<ExtVectorType>(LHSVecType)) {
10430 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10431 return LHSType;
10434 if (!IsCompAssign)
10435 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10436 return RHSType;
10439 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10440 // can be mixed, with the result being the non-bool type. The non-bool
10441 // operand must have integer element type.
10442 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10443 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10444 (Context.getTypeSize(LHSVecType->getElementType()) ==
10445 Context.getTypeSize(RHSVecType->getElementType()))) {
10446 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10447 LHSVecType->getElementType()->isIntegerType() &&
10448 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
10449 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10450 return LHSType;
10452 if (!IsCompAssign &&
10453 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10454 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10455 RHSVecType->getElementType()->isIntegerType()) {
10456 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10457 return RHSType;
10461 // Expressions containing fixed-length and sizeless SVE vectors are invalid
10462 // since the ambiguity can affect the ABI.
10463 auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
10464 const VectorType *VecType = SecondType->getAs<VectorType>();
10465 return FirstType->isSizelessBuiltinType() && VecType &&
10466 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
10467 VecType->getVectorKind() ==
10468 VectorType::SveFixedLengthPredicateVector);
10471 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
10472 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
10473 return QualType();
10476 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
10477 // since the ambiguity can affect the ABI.
10478 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
10479 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10480 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10482 if (FirstVecType && SecondVecType)
10483 return FirstVecType->getVectorKind() == VectorType::GenericVector &&
10484 (SecondVecType->getVectorKind() ==
10485 VectorType::SveFixedLengthDataVector ||
10486 SecondVecType->getVectorKind() ==
10487 VectorType::SveFixedLengthPredicateVector);
10489 return FirstType->isSizelessBuiltinType() && SecondVecType &&
10490 SecondVecType->getVectorKind() == VectorType::GenericVector;
10493 if (IsSveGnuConversion(LHSType, RHSType) ||
10494 IsSveGnuConversion(RHSType, LHSType)) {
10495 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
10496 return QualType();
10499 // If there's a vector type and a scalar, try to convert the scalar to
10500 // the vector element type and splat.
10501 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10502 if (!RHSVecType) {
10503 if (isa<ExtVectorType>(LHSVecType)) {
10504 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10505 LHSVecType->getElementType(), LHSType,
10506 DiagID))
10507 return LHSType;
10508 } else {
10509 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10510 return LHSType;
10513 if (!LHSVecType) {
10514 if (isa<ExtVectorType>(RHSVecType)) {
10515 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10516 LHSType, RHSVecType->getElementType(),
10517 RHSType, DiagID))
10518 return RHSType;
10519 } else {
10520 if (LHS.get()->isLValue() ||
10521 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10522 return RHSType;
10526 // FIXME: The code below also handles conversion between vectors and
10527 // non-scalars, we should break this down into fine grained specific checks
10528 // and emit proper diagnostics.
10529 QualType VecType = LHSVecType ? LHSType : RHSType;
10530 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10531 QualType OtherType = LHSVecType ? RHSType : LHSType;
10532 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10533 if (isLaxVectorConversion(OtherType, VecType)) {
10534 if (anyAltivecTypes(RHSType, LHSType) &&
10535 !areSameVectorElemTypes(RHSType, LHSType))
10536 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10537 // If we're allowing lax vector conversions, only the total (data) size
10538 // needs to be the same. For non compound assignment, if one of the types is
10539 // scalar, the result is always the vector type.
10540 if (!IsCompAssign) {
10541 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10542 return VecType;
10543 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10544 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10545 // type. Note that this is already done by non-compound assignments in
10546 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10547 // <1 x T> -> T. The result is also a vector type.
10548 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10549 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10550 ExprResult *RHSExpr = &RHS;
10551 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10552 return VecType;
10556 // Okay, the expression is invalid.
10558 // If there's a non-vector, non-real operand, diagnose that.
10559 if ((!RHSVecType && !RHSType->isRealType()) ||
10560 (!LHSVecType && !LHSType->isRealType())) {
10561 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10562 << LHSType << RHSType
10563 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10564 return QualType();
10567 // OpenCL V1.1 6.2.6.p1:
10568 // If the operands are of more than one vector type, then an error shall
10569 // occur. Implicit conversions between vector types are not permitted, per
10570 // section 6.2.1.
10571 if (getLangOpts().OpenCL &&
10572 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10573 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10574 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10575 << RHSType;
10576 return QualType();
10580 // If there is a vector type that is not a ExtVector and a scalar, we reach
10581 // this point if scalar could not be converted to the vector's element type
10582 // without truncation.
10583 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10584 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10585 QualType Scalar = LHSVecType ? RHSType : LHSType;
10586 QualType Vector = LHSVecType ? LHSType : RHSType;
10587 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10588 Diag(Loc,
10589 diag::err_typecheck_vector_not_convertable_implict_truncation)
10590 << ScalarOrVector << Scalar << Vector;
10592 return QualType();
10595 // Otherwise, use the generic diagnostic.
10596 Diag(Loc, DiagID)
10597 << LHSType << RHSType
10598 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10599 return QualType();
10602 QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
10603 SourceLocation Loc,
10604 bool IsCompAssign,
10605 ArithConvKind OperationKind) {
10606 if (!IsCompAssign) {
10607 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10608 if (LHS.isInvalid())
10609 return QualType();
10611 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10612 if (RHS.isInvalid())
10613 return QualType();
10615 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10616 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10618 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10619 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10621 unsigned DiagID = diag::err_typecheck_invalid_operands;
10622 if ((OperationKind == ACK_Arithmetic) &&
10623 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10624 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10625 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10626 << RHS.get()->getSourceRange();
10627 return QualType();
10630 if (Context.hasSameType(LHSType, RHSType))
10631 return LHSType;
10633 if (LHSType->isVLSTBuiltinType() && !RHSType->isVLSTBuiltinType()) {
10634 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10635 return LHSType;
10637 if (RHSType->isVLSTBuiltinType() && !LHSType->isVLSTBuiltinType()) {
10638 if (LHS.get()->isLValue() ||
10639 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10640 return RHSType;
10643 if ((!LHSType->isVLSTBuiltinType() && !LHSType->isRealType()) ||
10644 (!RHSType->isVLSTBuiltinType() && !RHSType->isRealType())) {
10645 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10646 << LHSType << RHSType << LHS.get()->getSourceRange()
10647 << RHS.get()->getSourceRange();
10648 return QualType();
10651 if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() &&
10652 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
10653 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
10654 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10655 << LHSType << RHSType << LHS.get()->getSourceRange()
10656 << RHS.get()->getSourceRange();
10657 return QualType();
10660 if (LHSType->isVLSTBuiltinType() || RHSType->isVLSTBuiltinType()) {
10661 QualType Scalar = LHSType->isVLSTBuiltinType() ? RHSType : LHSType;
10662 QualType Vector = LHSType->isVLSTBuiltinType() ? LHSType : RHSType;
10663 bool ScalarOrVector =
10664 LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType();
10666 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
10667 << ScalarOrVector << Scalar << Vector;
10669 return QualType();
10672 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10673 << RHS.get()->getSourceRange();
10674 return QualType();
10677 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
10678 // expression. These are mainly cases where the null pointer is used as an
10679 // integer instead of a pointer.
10680 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10681 SourceLocation Loc, bool IsCompare) {
10682 // The canonical way to check for a GNU null is with isNullPointerConstant,
10683 // but we use a bit of a hack here for speed; this is a relatively
10684 // hot path, and isNullPointerConstant is slow.
10685 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10686 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10688 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10690 // Avoid analyzing cases where the result will either be invalid (and
10691 // diagnosed as such) or entirely valid and not something to warn about.
10692 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10693 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10694 return;
10696 // Comparison operations would not make sense with a null pointer no matter
10697 // what the other expression is.
10698 if (!IsCompare) {
10699 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10700 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10701 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10702 return;
10705 // The rest of the operations only make sense with a null pointer
10706 // if the other expression is a pointer.
10707 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10708 NonNullType->canDecayToPointerType())
10709 return;
10711 S.Diag(Loc, diag::warn_null_in_comparison_operation)
10712 << LHSNull /* LHS is NULL */ << NonNullType
10713 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10716 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10717 SourceLocation Loc) {
10718 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10719 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10720 if (!LUE || !RUE)
10721 return;
10722 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10723 RUE->getKind() != UETT_SizeOf)
10724 return;
10726 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10727 QualType LHSTy = LHSArg->getType();
10728 QualType RHSTy;
10730 if (RUE->isArgumentType())
10731 RHSTy = RUE->getArgumentType().getNonReferenceType();
10732 else
10733 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10735 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10736 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10737 return;
10739 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10740 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10741 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10742 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10743 << LHSArgDecl;
10745 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10746 QualType ArrayElemTy = ArrayTy->getElementType();
10747 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10748 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10749 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10750 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10751 return;
10752 S.Diag(Loc, diag::warn_division_sizeof_array)
10753 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10754 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10755 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10756 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10757 << LHSArgDecl;
10760 S.Diag(Loc, diag::note_precedence_silence) << RHS;
10764 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10765 ExprResult &RHS,
10766 SourceLocation Loc, bool IsDiv) {
10767 // Check for division/remainder by zero.
10768 Expr::EvalResult RHSValue;
10769 if (!RHS.get()->isValueDependent() &&
10770 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10771 RHSValue.Val.getInt() == 0)
10772 S.DiagRuntimeBehavior(Loc, RHS.get(),
10773 S.PDiag(diag::warn_remainder_division_by_zero)
10774 << IsDiv << RHS.get()->getSourceRange());
10777 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10778 SourceLocation Loc,
10779 bool IsCompAssign, bool IsDiv) {
10780 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10782 QualType LHSTy = LHS.get()->getType();
10783 QualType RHSTy = RHS.get()->getType();
10784 if (LHSTy->isVectorType() || RHSTy->isVectorType())
10785 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10786 /*AllowBothBool*/ getLangOpts().AltiVec,
10787 /*AllowBoolConversions*/ false,
10788 /*AllowBooleanOperation*/ false,
10789 /*ReportInvalid*/ true);
10790 if (LHSTy->isVLSTBuiltinType() || RHSTy->isVLSTBuiltinType())
10791 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10792 ACK_Arithmetic);
10793 if (!IsDiv &&
10794 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10795 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10796 // For division, only matrix-by-scalar is supported. Other combinations with
10797 // matrix types are invalid.
10798 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10799 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10801 QualType compType = UsualArithmeticConversions(
10802 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10803 if (LHS.isInvalid() || RHS.isInvalid())
10804 return QualType();
10807 if (compType.isNull() || !compType->isArithmeticType())
10808 return InvalidOperands(Loc, LHS, RHS);
10809 if (IsDiv) {
10810 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10811 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10813 return compType;
10816 QualType Sema::CheckRemainderOperands(
10817 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10818 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10820 if (LHS.get()->getType()->isVectorType() ||
10821 RHS.get()->getType()->isVectorType()) {
10822 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10823 RHS.get()->getType()->hasIntegerRepresentation())
10824 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10825 /*AllowBothBool*/ getLangOpts().AltiVec,
10826 /*AllowBoolConversions*/ false,
10827 /*AllowBooleanOperation*/ false,
10828 /*ReportInvalid*/ true);
10829 return InvalidOperands(Loc, LHS, RHS);
10832 if (LHS.get()->getType()->isVLSTBuiltinType() ||
10833 RHS.get()->getType()->isVLSTBuiltinType()) {
10834 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10835 RHS.get()->getType()->hasIntegerRepresentation())
10836 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10837 ACK_Arithmetic);
10839 return InvalidOperands(Loc, LHS, RHS);
10842 QualType compType = UsualArithmeticConversions(
10843 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10844 if (LHS.isInvalid() || RHS.isInvalid())
10845 return QualType();
10847 if (compType.isNull() || !compType->isIntegerType())
10848 return InvalidOperands(Loc, LHS, RHS);
10849 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10850 return compType;
10853 /// Diagnose invalid arithmetic on two void pointers.
10854 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10855 Expr *LHSExpr, Expr *RHSExpr) {
10856 S.Diag(Loc, S.getLangOpts().CPlusPlus
10857 ? diag::err_typecheck_pointer_arith_void_type
10858 : diag::ext_gnu_void_ptr)
10859 << 1 /* two pointers */ << LHSExpr->getSourceRange()
10860 << RHSExpr->getSourceRange();
10863 /// Diagnose invalid arithmetic on a void pointer.
10864 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10865 Expr *Pointer) {
10866 S.Diag(Loc, S.getLangOpts().CPlusPlus
10867 ? diag::err_typecheck_pointer_arith_void_type
10868 : diag::ext_gnu_void_ptr)
10869 << 0 /* one pointer */ << Pointer->getSourceRange();
10872 /// Diagnose invalid arithmetic on a null pointer.
10874 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10875 /// idiom, which we recognize as a GNU extension.
10877 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10878 Expr *Pointer, bool IsGNUIdiom) {
10879 if (IsGNUIdiom)
10880 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10881 << Pointer->getSourceRange();
10882 else
10883 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10884 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10887 /// Diagnose invalid subraction on a null pointer.
10889 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
10890 Expr *Pointer, bool BothNull) {
10891 // Null - null is valid in C++ [expr.add]p7
10892 if (BothNull && S.getLangOpts().CPlusPlus)
10893 return;
10895 // Is this s a macro from a system header?
10896 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
10897 return;
10899 S.DiagRuntimeBehavior(Loc, Pointer,
10900 S.PDiag(diag::warn_pointer_sub_null_ptr)
10901 << S.getLangOpts().CPlusPlus
10902 << Pointer->getSourceRange());
10905 /// Diagnose invalid arithmetic on two function pointers.
10906 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10907 Expr *LHS, Expr *RHS) {
10908 assert(LHS->getType()->isAnyPointerType());
10909 assert(RHS->getType()->isAnyPointerType());
10910 S.Diag(Loc, S.getLangOpts().CPlusPlus
10911 ? diag::err_typecheck_pointer_arith_function_type
10912 : diag::ext_gnu_ptr_func_arith)
10913 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10914 // We only show the second type if it differs from the first.
10915 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10916 RHS->getType())
10917 << RHS->getType()->getPointeeType()
10918 << LHS->getSourceRange() << RHS->getSourceRange();
10921 /// Diagnose invalid arithmetic on a function pointer.
10922 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10923 Expr *Pointer) {
10924 assert(Pointer->getType()->isAnyPointerType());
10925 S.Diag(Loc, S.getLangOpts().CPlusPlus
10926 ? diag::err_typecheck_pointer_arith_function_type
10927 : diag::ext_gnu_ptr_func_arith)
10928 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10929 << 0 /* one pointer, so only one type */
10930 << Pointer->getSourceRange();
10933 /// Emit error if Operand is incomplete pointer type
10935 /// \returns True if pointer has incomplete type
10936 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10937 Expr *Operand) {
10938 QualType ResType = Operand->getType();
10939 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10940 ResType = ResAtomicType->getValueType();
10942 assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10943 QualType PointeeTy = ResType->getPointeeType();
10944 return S.RequireCompleteSizedType(
10945 Loc, PointeeTy,
10946 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10947 Operand->getSourceRange());
10950 /// Check the validity of an arithmetic pointer operand.
10952 /// If the operand has pointer type, this code will check for pointer types
10953 /// which are invalid in arithmetic operations. These will be diagnosed
10954 /// appropriately, including whether or not the use is supported as an
10955 /// extension.
10957 /// \returns True when the operand is valid to use (even if as an extension).
10958 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10959 Expr *Operand) {
10960 QualType ResType = Operand->getType();
10961 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10962 ResType = ResAtomicType->getValueType();
10964 if (!ResType->isAnyPointerType()) return true;
10966 QualType PointeeTy = ResType->getPointeeType();
10967 if (PointeeTy->isVoidType()) {
10968 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10969 return !S.getLangOpts().CPlusPlus;
10971 if (PointeeTy->isFunctionType()) {
10972 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10973 return !S.getLangOpts().CPlusPlus;
10976 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10978 return true;
10981 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10982 /// operands.
10984 /// This routine will diagnose any invalid arithmetic on pointer operands much
10985 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10986 /// for emitting a single diagnostic even for operations where both LHS and RHS
10987 /// are (potentially problematic) pointers.
10989 /// \returns True when the operand is valid to use (even if as an extension).
10990 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10991 Expr *LHSExpr, Expr *RHSExpr) {
10992 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10993 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10994 if (!isLHSPointer && !isRHSPointer) return true;
10996 QualType LHSPointeeTy, RHSPointeeTy;
10997 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10998 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11000 // if both are pointers check if operation is valid wrt address spaces
11001 if (isLHSPointer && isRHSPointer) {
11002 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
11003 S.Diag(Loc,
11004 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11005 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11006 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11007 return false;
11011 // Check for arithmetic on pointers to incomplete types.
11012 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11013 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11014 if (isLHSVoidPtr || isRHSVoidPtr) {
11015 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
11016 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
11017 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11019 return !S.getLangOpts().CPlusPlus;
11022 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11023 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11024 if (isLHSFuncPtr || isRHSFuncPtr) {
11025 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
11026 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11027 RHSExpr);
11028 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
11030 return !S.getLangOpts().CPlusPlus;
11033 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11034 return false;
11035 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11036 return false;
11038 return true;
11041 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11042 /// literal.
11043 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
11044 Expr *LHSExpr, Expr *RHSExpr) {
11045 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11046 Expr* IndexExpr = RHSExpr;
11047 if (!StrExpr) {
11048 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11049 IndexExpr = LHSExpr;
11052 bool IsStringPlusInt = StrExpr &&
11053 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
11054 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11055 return;
11057 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11058 Self.Diag(OpLoc, diag::warn_string_plus_int)
11059 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11061 // Only print a fixit for "str" + int, not for int + "str".
11062 if (IndexExpr == RHSExpr) {
11063 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11064 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11065 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11066 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11067 << FixItHint::CreateInsertion(EndLoc, "]");
11068 } else
11069 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11072 /// Emit a warning when adding a char literal to a string.
11073 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11074 Expr *LHSExpr, Expr *RHSExpr) {
11075 const Expr *StringRefExpr = LHSExpr;
11076 const CharacterLiteral *CharExpr =
11077 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11079 if (!CharExpr) {
11080 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11081 StringRefExpr = RHSExpr;
11084 if (!CharExpr || !StringRefExpr)
11085 return;
11087 const QualType StringType = StringRefExpr->getType();
11089 // Return if not a PointerType.
11090 if (!StringType->isAnyPointerType())
11091 return;
11093 // Return if not a CharacterType.
11094 if (!StringType->getPointeeType()->isAnyCharacterType())
11095 return;
11097 ASTContext &Ctx = Self.getASTContext();
11098 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11100 const QualType CharType = CharExpr->getType();
11101 if (!CharType->isAnyCharacterType() &&
11102 CharType->isIntegerType() &&
11103 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11104 Self.Diag(OpLoc, diag::warn_string_plus_char)
11105 << DiagRange << Ctx.CharTy;
11106 } else {
11107 Self.Diag(OpLoc, diag::warn_string_plus_char)
11108 << DiagRange << CharExpr->getType();
11111 // Only print a fixit for str + char, not for char + str.
11112 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11113 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11114 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11115 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11116 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11117 << FixItHint::CreateInsertion(EndLoc, "]");
11118 } else {
11119 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11123 /// Emit error when two pointers are incompatible.
11124 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11125 Expr *LHSExpr, Expr *RHSExpr) {
11126 assert(LHSExpr->getType()->isAnyPointerType());
11127 assert(RHSExpr->getType()->isAnyPointerType());
11128 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11129 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11130 << RHSExpr->getSourceRange();
11133 // C99 6.5.6
11134 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11135 SourceLocation Loc, BinaryOperatorKind Opc,
11136 QualType* CompLHSTy) {
11137 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11139 if (LHS.get()->getType()->isVectorType() ||
11140 RHS.get()->getType()->isVectorType()) {
11141 QualType compType =
11142 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11143 /*AllowBothBool*/ getLangOpts().AltiVec,
11144 /*AllowBoolConversions*/ getLangOpts().ZVector,
11145 /*AllowBooleanOperation*/ false,
11146 /*ReportInvalid*/ true);
11147 if (CompLHSTy) *CompLHSTy = compType;
11148 return compType;
11151 if (LHS.get()->getType()->isVLSTBuiltinType() ||
11152 RHS.get()->getType()->isVLSTBuiltinType()) {
11153 QualType compType =
11154 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11155 if (CompLHSTy)
11156 *CompLHSTy = compType;
11157 return compType;
11160 if (LHS.get()->getType()->isConstantMatrixType() ||
11161 RHS.get()->getType()->isConstantMatrixType()) {
11162 QualType compType =
11163 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11164 if (CompLHSTy)
11165 *CompLHSTy = compType;
11166 return compType;
11169 QualType compType = UsualArithmeticConversions(
11170 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11171 if (LHS.isInvalid() || RHS.isInvalid())
11172 return QualType();
11174 // Diagnose "string literal" '+' int and string '+' "char literal".
11175 if (Opc == BO_Add) {
11176 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11177 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11180 // handle the common case first (both operands are arithmetic).
11181 if (!compType.isNull() && compType->isArithmeticType()) {
11182 if (CompLHSTy) *CompLHSTy = compType;
11183 return compType;
11186 // Type-checking. Ultimately the pointer's going to be in PExp;
11187 // note that we bias towards the LHS being the pointer.
11188 Expr *PExp = LHS.get(), *IExp = RHS.get();
11190 bool isObjCPointer;
11191 if (PExp->getType()->isPointerType()) {
11192 isObjCPointer = false;
11193 } else if (PExp->getType()->isObjCObjectPointerType()) {
11194 isObjCPointer = true;
11195 } else {
11196 std::swap(PExp, IExp);
11197 if (PExp->getType()->isPointerType()) {
11198 isObjCPointer = false;
11199 } else if (PExp->getType()->isObjCObjectPointerType()) {
11200 isObjCPointer = true;
11201 } else {
11202 return InvalidOperands(Loc, LHS, RHS);
11205 assert(PExp->getType()->isAnyPointerType());
11207 if (!IExp->getType()->isIntegerType())
11208 return InvalidOperands(Loc, LHS, RHS);
11210 // Adding to a null pointer results in undefined behavior.
11211 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11212 Context, Expr::NPC_ValueDependentIsNotNull)) {
11213 // In C++ adding zero to a null pointer is defined.
11214 Expr::EvalResult KnownVal;
11215 if (!getLangOpts().CPlusPlus ||
11216 (!IExp->isValueDependent() &&
11217 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11218 KnownVal.Val.getInt() != 0))) {
11219 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11220 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11221 Context, BO_Add, PExp, IExp);
11222 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11226 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11227 return QualType();
11229 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11230 return QualType();
11232 // Check array bounds for pointer arithemtic
11233 CheckArrayAccess(PExp, IExp);
11235 if (CompLHSTy) {
11236 QualType LHSTy = Context.isPromotableBitField(LHS.get());
11237 if (LHSTy.isNull()) {
11238 LHSTy = LHS.get()->getType();
11239 if (LHSTy->isPromotableIntegerType())
11240 LHSTy = Context.getPromotedIntegerType(LHSTy);
11242 *CompLHSTy = LHSTy;
11245 return PExp->getType();
11248 // C99 6.5.6
11249 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11250 SourceLocation Loc,
11251 QualType* CompLHSTy) {
11252 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11254 if (LHS.get()->getType()->isVectorType() ||
11255 RHS.get()->getType()->isVectorType()) {
11256 QualType compType =
11257 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11258 /*AllowBothBool*/ getLangOpts().AltiVec,
11259 /*AllowBoolConversions*/ getLangOpts().ZVector,
11260 /*AllowBooleanOperation*/ false,
11261 /*ReportInvalid*/ true);
11262 if (CompLHSTy) *CompLHSTy = compType;
11263 return compType;
11266 if (LHS.get()->getType()->isVLSTBuiltinType() ||
11267 RHS.get()->getType()->isVLSTBuiltinType()) {
11268 QualType compType =
11269 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11270 if (CompLHSTy)
11271 *CompLHSTy = compType;
11272 return compType;
11275 if (LHS.get()->getType()->isConstantMatrixType() ||
11276 RHS.get()->getType()->isConstantMatrixType()) {
11277 QualType compType =
11278 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11279 if (CompLHSTy)
11280 *CompLHSTy = compType;
11281 return compType;
11284 QualType compType = UsualArithmeticConversions(
11285 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11286 if (LHS.isInvalid() || RHS.isInvalid())
11287 return QualType();
11289 // Enforce type constraints: C99 6.5.6p3.
11291 // Handle the common case first (both operands are arithmetic).
11292 if (!compType.isNull() && compType->isArithmeticType()) {
11293 if (CompLHSTy) *CompLHSTy = compType;
11294 return compType;
11297 // Either ptr - int or ptr - ptr.
11298 if (LHS.get()->getType()->isAnyPointerType()) {
11299 QualType lpointee = LHS.get()->getType()->getPointeeType();
11301 // Diagnose bad cases where we step over interface counts.
11302 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11303 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11304 return QualType();
11306 // The result type of a pointer-int computation is the pointer type.
11307 if (RHS.get()->getType()->isIntegerType()) {
11308 // Subtracting from a null pointer should produce a warning.
11309 // The last argument to the diagnose call says this doesn't match the
11310 // GNU int-to-pointer idiom.
11311 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
11312 Expr::NPC_ValueDependentIsNotNull)) {
11313 // In C++ adding zero to a null pointer is defined.
11314 Expr::EvalResult KnownVal;
11315 if (!getLangOpts().CPlusPlus ||
11316 (!RHS.get()->isValueDependent() &&
11317 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11318 KnownVal.Val.getInt() != 0))) {
11319 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11323 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11324 return QualType();
11326 // Check array bounds for pointer arithemtic
11327 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11328 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11330 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11331 return LHS.get()->getType();
11334 // Handle pointer-pointer subtractions.
11335 if (const PointerType *RHSPTy
11336 = RHS.get()->getType()->getAs<PointerType>()) {
11337 QualType rpointee = RHSPTy->getPointeeType();
11339 if (getLangOpts().CPlusPlus) {
11340 // Pointee types must be the same: C++ [expr.add]
11341 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11342 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11344 } else {
11345 // Pointee types must be compatible C99 6.5.6p3
11346 if (!Context.typesAreCompatible(
11347 Context.getCanonicalType(lpointee).getUnqualifiedType(),
11348 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11349 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11350 return QualType();
11354 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
11355 LHS.get(), RHS.get()))
11356 return QualType();
11358 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11359 Context, Expr::NPC_ValueDependentIsNotNull);
11360 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11361 Context, Expr::NPC_ValueDependentIsNotNull);
11363 // Subtracting nullptr or from nullptr is suspect
11364 if (LHSIsNullPtr)
11365 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11366 if (RHSIsNullPtr)
11367 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11369 // The pointee type may have zero size. As an extension, a structure or
11370 // union may have zero size or an array may have zero length. In this
11371 // case subtraction does not make sense.
11372 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11373 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11374 if (ElementSize.isZero()) {
11375 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11376 << rpointee.getUnqualifiedType()
11377 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11381 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11382 return Context.getPointerDiffType();
11386 return InvalidOperands(Loc, LHS, RHS);
11389 static bool isScopedEnumerationType(QualType T) {
11390 if (const EnumType *ET = T->getAs<EnumType>())
11391 return ET->getDecl()->isScoped();
11392 return false;
11395 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
11396 SourceLocation Loc, BinaryOperatorKind Opc,
11397 QualType LHSType) {
11398 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11399 // so skip remaining warnings as we don't want to modify values within Sema.
11400 if (S.getLangOpts().OpenCL)
11401 return;
11403 // Check right/shifter operand
11404 Expr::EvalResult RHSResult;
11405 if (RHS.get()->isValueDependent() ||
11406 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11407 return;
11408 llvm::APSInt Right = RHSResult.Val.getInt();
11410 if (Right.isNegative()) {
11411 S.DiagRuntimeBehavior(Loc, RHS.get(),
11412 S.PDiag(diag::warn_shift_negative)
11413 << RHS.get()->getSourceRange());
11414 return;
11417 QualType LHSExprType = LHS.get()->getType();
11418 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11419 if (LHSExprType->isBitIntType())
11420 LeftSize = S.Context.getIntWidth(LHSExprType);
11421 else if (LHSExprType->isFixedPointType()) {
11422 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11423 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11425 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
11426 if (Right.uge(LeftBits)) {
11427 S.DiagRuntimeBehavior(Loc, RHS.get(),
11428 S.PDiag(diag::warn_shift_gt_typewidth)
11429 << RHS.get()->getSourceRange());
11430 return;
11433 // FIXME: We probably need to handle fixed point types specially here.
11434 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11435 return;
11437 // When left shifting an ICE which is signed, we can check for overflow which
11438 // according to C++ standards prior to C++2a has undefined behavior
11439 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11440 // more than the maximum value representable in the result type, so never
11441 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11442 // expression is still probably a bug.)
11443 Expr::EvalResult LHSResult;
11444 if (LHS.get()->isValueDependent() ||
11445 LHSType->hasUnsignedIntegerRepresentation() ||
11446 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11447 return;
11448 llvm::APSInt Left = LHSResult.Val.getInt();
11450 // Don't warn if signed overflow is defined, then all the rest of the
11451 // diagnostics will not be triggered because the behavior is defined.
11452 // Also don't warn in C++20 mode (and newer), as signed left shifts
11453 // always wrap and never overflow.
11454 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11455 return;
11457 // If LHS does not have a non-negative value then, the
11458 // behavior is undefined before C++2a. Warn about it.
11459 if (Left.isNegative()) {
11460 S.DiagRuntimeBehavior(Loc, LHS.get(),
11461 S.PDiag(diag::warn_shift_lhs_negative)
11462 << LHS.get()->getSourceRange());
11463 return;
11466 llvm::APInt ResultBits =
11467 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
11468 if (LeftBits.uge(ResultBits))
11469 return;
11470 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11471 Result = Result.shl(Right);
11473 // Print the bit representation of the signed integer as an unsigned
11474 // hexadecimal number.
11475 SmallString<40> HexResult;
11476 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11478 // If we are only missing a sign bit, this is less likely to result in actual
11479 // bugs -- if the result is cast back to an unsigned type, it will have the
11480 // expected value. Thus we place this behind a different warning that can be
11481 // turned off separately if needed.
11482 if (LeftBits == ResultBits - 1) {
11483 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11484 << HexResult << LHSType
11485 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11486 return;
11489 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11490 << HexResult.str() << Result.getMinSignedBits() << LHSType
11491 << Left.getBitWidth() << LHS.get()->getSourceRange()
11492 << RHS.get()->getSourceRange();
11495 /// Return the resulting type when a vector is shifted
11496 /// by a scalar or vector shift amount.
11497 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
11498 SourceLocation Loc, bool IsCompAssign) {
11499 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11500 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11501 !LHS.get()->getType()->isVectorType()) {
11502 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11503 << RHS.get()->getType() << LHS.get()->getType()
11504 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11505 return QualType();
11508 if (!IsCompAssign) {
11509 LHS = S.UsualUnaryConversions(LHS.get());
11510 if (LHS.isInvalid()) return QualType();
11513 RHS = S.UsualUnaryConversions(RHS.get());
11514 if (RHS.isInvalid()) return QualType();
11516 QualType LHSType = LHS.get()->getType();
11517 // Note that LHS might be a scalar because the routine calls not only in
11518 // OpenCL case.
11519 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11520 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11522 // Note that RHS might not be a vector.
11523 QualType RHSType = RHS.get()->getType();
11524 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11525 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11527 // Do not allow shifts for boolean vectors.
11528 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11529 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11530 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11531 << LHS.get()->getType() << RHS.get()->getType()
11532 << LHS.get()->getSourceRange();
11533 return QualType();
11536 // The operands need to be integers.
11537 if (!LHSEleType->isIntegerType()) {
11538 S.Diag(Loc, diag::err_typecheck_expect_int)
11539 << LHS.get()->getType() << LHS.get()->getSourceRange();
11540 return QualType();
11543 if (!RHSEleType->isIntegerType()) {
11544 S.Diag(Loc, diag::err_typecheck_expect_int)
11545 << RHS.get()->getType() << RHS.get()->getSourceRange();
11546 return QualType();
11549 if (!LHSVecTy) {
11550 assert(RHSVecTy);
11551 if (IsCompAssign)
11552 return RHSType;
11553 if (LHSEleType != RHSEleType) {
11554 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11555 LHSEleType = RHSEleType;
11557 QualType VecTy =
11558 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11559 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11560 LHSType = VecTy;
11561 } else if (RHSVecTy) {
11562 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11563 // are applied component-wise. So if RHS is a vector, then ensure
11564 // that the number of elements is the same as LHS...
11565 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11566 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11567 << LHS.get()->getType() << RHS.get()->getType()
11568 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11569 return QualType();
11571 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11572 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11573 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11574 if (LHSBT != RHSBT &&
11575 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11576 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11577 << LHS.get()->getType() << RHS.get()->getType()
11578 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11581 } else {
11582 // ...else expand RHS to match the number of elements in LHS.
11583 QualType VecTy =
11584 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11585 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11588 return LHSType;
11591 static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
11592 ExprResult &RHS, SourceLocation Loc,
11593 bool IsCompAssign) {
11594 if (!IsCompAssign) {
11595 LHS = S.UsualUnaryConversions(LHS.get());
11596 if (LHS.isInvalid())
11597 return QualType();
11600 RHS = S.UsualUnaryConversions(RHS.get());
11601 if (RHS.isInvalid())
11602 return QualType();
11604 QualType LHSType = LHS.get()->getType();
11605 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11606 QualType LHSEleType = LHSType->isVLSTBuiltinType()
11607 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
11608 : LHSType;
11610 // Note that RHS might not be a vector
11611 QualType RHSType = RHS.get()->getType();
11612 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11613 QualType RHSEleType = RHSType->isVLSTBuiltinType()
11614 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
11615 : RHSType;
11617 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11618 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11619 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11620 << LHSType << RHSType << LHS.get()->getSourceRange();
11621 return QualType();
11624 if (!LHSEleType->isIntegerType()) {
11625 S.Diag(Loc, diag::err_typecheck_expect_int)
11626 << LHS.get()->getType() << LHS.get()->getSourceRange();
11627 return QualType();
11630 if (!RHSEleType->isIntegerType()) {
11631 S.Diag(Loc, diag::err_typecheck_expect_int)
11632 << RHS.get()->getType() << RHS.get()->getSourceRange();
11633 return QualType();
11636 if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() &&
11637 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11638 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
11639 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11640 << LHSType << RHSType << LHS.get()->getSourceRange()
11641 << RHS.get()->getSourceRange();
11642 return QualType();
11645 if (!LHSType->isVLSTBuiltinType()) {
11646 assert(RHSType->isVLSTBuiltinType());
11647 if (IsCompAssign)
11648 return RHSType;
11649 if (LHSEleType != RHSEleType) {
11650 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
11651 LHSEleType = RHSEleType;
11653 const llvm::ElementCount VecSize =
11654 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
11655 QualType VecTy =
11656 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
11657 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
11658 LHSType = VecTy;
11659 } else if (RHSBuiltinTy && RHSBuiltinTy->isVLSTBuiltinType()) {
11660 if (S.Context.getTypeSize(RHSBuiltinTy) !=
11661 S.Context.getTypeSize(LHSBuiltinTy)) {
11662 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11663 << LHSType << RHSType << LHS.get()->getSourceRange()
11664 << RHS.get()->getSourceRange();
11665 return QualType();
11667 } else {
11668 const llvm::ElementCount VecSize =
11669 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
11670 if (LHSEleType != RHSEleType) {
11671 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
11672 RHSEleType = LHSEleType;
11674 QualType VecTy =
11675 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
11676 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11679 return LHSType;
11682 // C99 6.5.7
11683 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
11684 SourceLocation Loc, BinaryOperatorKind Opc,
11685 bool IsCompAssign) {
11686 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11688 // Vector shifts promote their scalar inputs to vector type.
11689 if (LHS.get()->getType()->isVectorType() ||
11690 RHS.get()->getType()->isVectorType()) {
11691 if (LangOpts.ZVector) {
11692 // The shift operators for the z vector extensions work basically
11693 // like general shifts, except that neither the LHS nor the RHS is
11694 // allowed to be a "vector bool".
11695 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11696 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
11697 return InvalidOperands(Loc, LHS, RHS);
11698 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11699 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
11700 return InvalidOperands(Loc, LHS, RHS);
11702 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11705 if (LHS.get()->getType()->isVLSTBuiltinType() ||
11706 RHS.get()->getType()->isVLSTBuiltinType())
11707 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11709 // Shifts don't perform usual arithmetic conversions, they just do integer
11710 // promotions on each operand. C99 6.5.7p3
11712 // For the LHS, do usual unary conversions, but then reset them away
11713 // if this is a compound assignment.
11714 ExprResult OldLHS = LHS;
11715 LHS = UsualUnaryConversions(LHS.get());
11716 if (LHS.isInvalid())
11717 return QualType();
11718 QualType LHSType = LHS.get()->getType();
11719 if (IsCompAssign) LHS = OldLHS;
11721 // The RHS is simpler.
11722 RHS = UsualUnaryConversions(RHS.get());
11723 if (RHS.isInvalid())
11724 return QualType();
11725 QualType RHSType = RHS.get()->getType();
11727 // C99 6.5.7p2: Each of the operands shall have integer type.
11728 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11729 if ((!LHSType->isFixedPointOrIntegerType() &&
11730 !LHSType->hasIntegerRepresentation()) ||
11731 !RHSType->hasIntegerRepresentation())
11732 return InvalidOperands(Loc, LHS, RHS);
11734 // C++0x: Don't allow scoped enums. FIXME: Use something better than
11735 // hasIntegerRepresentation() above instead of this.
11736 if (isScopedEnumerationType(LHSType) ||
11737 isScopedEnumerationType(RHSType)) {
11738 return InvalidOperands(Loc, LHS, RHS);
11740 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11742 // "The type of the result is that of the promoted left operand."
11743 return LHSType;
11746 /// Diagnose bad pointer comparisons.
11747 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
11748 ExprResult &LHS, ExprResult &RHS,
11749 bool IsError) {
11750 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11751 : diag::ext_typecheck_comparison_of_distinct_pointers)
11752 << LHS.get()->getType() << RHS.get()->getType()
11753 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11756 /// Returns false if the pointers are converted to a composite type,
11757 /// true otherwise.
11758 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
11759 ExprResult &LHS, ExprResult &RHS) {
11760 // C++ [expr.rel]p2:
11761 // [...] Pointer conversions (4.10) and qualification
11762 // conversions (4.4) are performed on pointer operands (or on
11763 // a pointer operand and a null pointer constant) to bring
11764 // them to their composite pointer type. [...]
11766 // C++ [expr.eq]p1 uses the same notion for (in)equality
11767 // comparisons of pointers.
11769 QualType LHSType = LHS.get()->getType();
11770 QualType RHSType = RHS.get()->getType();
11771 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11772 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11774 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11775 if (T.isNull()) {
11776 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11777 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11778 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11779 else
11780 S.InvalidOperands(Loc, LHS, RHS);
11781 return true;
11784 return false;
11787 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
11788 ExprResult &LHS,
11789 ExprResult &RHS,
11790 bool IsError) {
11791 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11792 : diag::ext_typecheck_comparison_of_fptr_to_void)
11793 << LHS.get()->getType() << RHS.get()->getType()
11794 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11797 static bool isObjCObjectLiteral(ExprResult &E) {
11798 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11799 case Stmt::ObjCArrayLiteralClass:
11800 case Stmt::ObjCDictionaryLiteralClass:
11801 case Stmt::ObjCStringLiteralClass:
11802 case Stmt::ObjCBoxedExprClass:
11803 return true;
11804 default:
11805 // Note that ObjCBoolLiteral is NOT an object literal!
11806 return false;
11810 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11811 const ObjCObjectPointerType *Type =
11812 LHS->getType()->getAs<ObjCObjectPointerType>();
11814 // If this is not actually an Objective-C object, bail out.
11815 if (!Type)
11816 return false;
11818 // Get the LHS object's interface type.
11819 QualType InterfaceType = Type->getPointeeType();
11821 // If the RHS isn't an Objective-C object, bail out.
11822 if (!RHS->getType()->isObjCObjectPointerType())
11823 return false;
11825 // Try to find the -isEqual: method.
11826 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
11827 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
11828 InterfaceType,
11829 /*IsInstance=*/true);
11830 if (!Method) {
11831 if (Type->isObjCIdType()) {
11832 // For 'id', just check the global pool.
11833 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
11834 /*receiverId=*/true);
11835 } else {
11836 // Check protocols.
11837 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
11838 /*IsInstance=*/true);
11842 if (!Method)
11843 return false;
11845 QualType T = Method->parameters()[0]->getType();
11846 if (!T->isObjCObjectPointerType())
11847 return false;
11849 QualType R = Method->getReturnType();
11850 if (!R->isScalarType())
11851 return false;
11853 return true;
11856 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
11857 FromE = FromE->IgnoreParenImpCasts();
11858 switch (FromE->getStmtClass()) {
11859 default:
11860 break;
11861 case Stmt::ObjCStringLiteralClass:
11862 // "string literal"
11863 return LK_String;
11864 case Stmt::ObjCArrayLiteralClass:
11865 // "array literal"
11866 return LK_Array;
11867 case Stmt::ObjCDictionaryLiteralClass:
11868 // "dictionary literal"
11869 return LK_Dictionary;
11870 case Stmt::BlockExprClass:
11871 return LK_Block;
11872 case Stmt::ObjCBoxedExprClass: {
11873 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
11874 switch (Inner->getStmtClass()) {
11875 case Stmt::IntegerLiteralClass:
11876 case Stmt::FloatingLiteralClass:
11877 case Stmt::CharacterLiteralClass:
11878 case Stmt::ObjCBoolLiteralExprClass:
11879 case Stmt::CXXBoolLiteralExprClass:
11880 // "numeric literal"
11881 return LK_Numeric;
11882 case Stmt::ImplicitCastExprClass: {
11883 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11884 // Boolean literals can be represented by implicit casts.
11885 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11886 return LK_Numeric;
11887 break;
11889 default:
11890 break;
11892 return LK_Boxed;
11895 return LK_None;
11898 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11899 ExprResult &LHS, ExprResult &RHS,
11900 BinaryOperator::Opcode Opc){
11901 Expr *Literal;
11902 Expr *Other;
11903 if (isObjCObjectLiteral(LHS)) {
11904 Literal = LHS.get();
11905 Other = RHS.get();
11906 } else {
11907 Literal = RHS.get();
11908 Other = LHS.get();
11911 // Don't warn on comparisons against nil.
11912 Other = Other->IgnoreParenCasts();
11913 if (Other->isNullPointerConstant(S.getASTContext(),
11914 Expr::NPC_ValueDependentIsNotNull))
11915 return;
11917 // This should be kept in sync with warn_objc_literal_comparison.
11918 // LK_String should always be after the other literals, since it has its own
11919 // warning flag.
11920 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11921 assert(LiteralKind != Sema::LK_Block);
11922 if (LiteralKind == Sema::LK_None) {
11923 llvm_unreachable("Unknown Objective-C object literal kind");
11926 if (LiteralKind == Sema::LK_String)
11927 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11928 << Literal->getSourceRange();
11929 else
11930 S.Diag(Loc, diag::warn_objc_literal_comparison)
11931 << LiteralKind << Literal->getSourceRange();
11933 if (BinaryOperator::isEqualityOp(Opc) &&
11934 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11935 SourceLocation Start = LHS.get()->getBeginLoc();
11936 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11937 CharSourceRange OpRange =
11938 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11940 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11941 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11942 << FixItHint::CreateReplacement(OpRange, " isEqual:")
11943 << FixItHint::CreateInsertion(End, "]");
11947 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11948 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11949 ExprResult &RHS, SourceLocation Loc,
11950 BinaryOperatorKind Opc) {
11951 // Check that left hand side is !something.
11952 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11953 if (!UO || UO->getOpcode() != UO_LNot) return;
11955 // Only check if the right hand side is non-bool arithmetic type.
11956 if (RHS.get()->isKnownToHaveBooleanValue()) return;
11958 // Make sure that the something in !something is not bool.
11959 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11960 if (SubExpr->isKnownToHaveBooleanValue()) return;
11962 // Emit warning.
11963 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11964 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11965 << Loc << IsBitwiseOp;
11967 // First note suggest !(x < y)
11968 SourceLocation FirstOpen = SubExpr->getBeginLoc();
11969 SourceLocation FirstClose = RHS.get()->getEndLoc();
11970 FirstClose = S.getLocForEndOfToken(FirstClose);
11971 if (FirstClose.isInvalid())
11972 FirstOpen = SourceLocation();
11973 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11974 << IsBitwiseOp
11975 << FixItHint::CreateInsertion(FirstOpen, "(")
11976 << FixItHint::CreateInsertion(FirstClose, ")");
11978 // Second note suggests (!x) < y
11979 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11980 SourceLocation SecondClose = LHS.get()->getEndLoc();
11981 SecondClose = S.getLocForEndOfToken(SecondClose);
11982 if (SecondClose.isInvalid())
11983 SecondOpen = SourceLocation();
11984 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11985 << FixItHint::CreateInsertion(SecondOpen, "(")
11986 << FixItHint::CreateInsertion(SecondClose, ")");
11989 // Returns true if E refers to a non-weak array.
11990 static bool checkForArray(const Expr *E) {
11991 const ValueDecl *D = nullptr;
11992 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11993 D = DR->getDecl();
11994 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11995 if (Mem->isImplicitAccess())
11996 D = Mem->getMemberDecl();
11998 if (!D)
11999 return false;
12000 return D->getType()->isArrayType() && !D->isWeak();
12003 /// Diagnose some forms of syntactically-obvious tautological comparison.
12004 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
12005 Expr *LHS, Expr *RHS,
12006 BinaryOperatorKind Opc) {
12007 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12008 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12010 QualType LHSType = LHS->getType();
12011 QualType RHSType = RHS->getType();
12012 if (LHSType->hasFloatingRepresentation() ||
12013 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12014 S.inTemplateInstantiation())
12015 return;
12017 // Comparisons between two array types are ill-formed for operator<=>, so
12018 // we shouldn't emit any additional warnings about it.
12019 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12020 return;
12022 // For non-floating point types, check for self-comparisons of the form
12023 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12024 // often indicate logic errors in the program.
12026 // NOTE: Don't warn about comparison expressions resulting from macro
12027 // expansion. Also don't warn about comparisons which are only self
12028 // comparisons within a template instantiation. The warnings should catch
12029 // obvious cases in the definition of the template anyways. The idea is to
12030 // warn when the typed comparison operator will always evaluate to the same
12031 // result.
12033 // Used for indexing into %select in warn_comparison_always
12034 enum {
12035 AlwaysConstant,
12036 AlwaysTrue,
12037 AlwaysFalse,
12038 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12041 // C++2a [depr.array.comp]:
12042 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12043 // operands of array type are deprecated.
12044 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
12045 RHSStripped->getType()->isArrayType()) {
12046 S.Diag(Loc, diag::warn_depr_array_comparison)
12047 << LHS->getSourceRange() << RHS->getSourceRange()
12048 << LHSStripped->getType() << RHSStripped->getType();
12049 // Carry on to produce the tautological comparison warning, if this
12050 // expression is potentially-evaluated, we can resolve the array to a
12051 // non-weak declaration, and so on.
12054 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12055 if (Expr::isSameComparisonOperand(LHS, RHS)) {
12056 unsigned Result;
12057 switch (Opc) {
12058 case BO_EQ:
12059 case BO_LE:
12060 case BO_GE:
12061 Result = AlwaysTrue;
12062 break;
12063 case BO_NE:
12064 case BO_LT:
12065 case BO_GT:
12066 Result = AlwaysFalse;
12067 break;
12068 case BO_Cmp:
12069 Result = AlwaysEqual;
12070 break;
12071 default:
12072 Result = AlwaysConstant;
12073 break;
12075 S.DiagRuntimeBehavior(Loc, nullptr,
12076 S.PDiag(diag::warn_comparison_always)
12077 << 0 /*self-comparison*/
12078 << Result);
12079 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12080 // What is it always going to evaluate to?
12081 unsigned Result;
12082 switch (Opc) {
12083 case BO_EQ: // e.g. array1 == array2
12084 Result = AlwaysFalse;
12085 break;
12086 case BO_NE: // e.g. array1 != array2
12087 Result = AlwaysTrue;
12088 break;
12089 default: // e.g. array1 <= array2
12090 // The best we can say is 'a constant'
12091 Result = AlwaysConstant;
12092 break;
12094 S.DiagRuntimeBehavior(Loc, nullptr,
12095 S.PDiag(diag::warn_comparison_always)
12096 << 1 /*array comparison*/
12097 << Result);
12101 if (isa<CastExpr>(LHSStripped))
12102 LHSStripped = LHSStripped->IgnoreParenCasts();
12103 if (isa<CastExpr>(RHSStripped))
12104 RHSStripped = RHSStripped->IgnoreParenCasts();
12106 // Warn about comparisons against a string constant (unless the other
12107 // operand is null); the user probably wants string comparison function.
12108 Expr *LiteralString = nullptr;
12109 Expr *LiteralStringStripped = nullptr;
12110 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12111 !RHSStripped->isNullPointerConstant(S.Context,
12112 Expr::NPC_ValueDependentIsNull)) {
12113 LiteralString = LHS;
12114 LiteralStringStripped = LHSStripped;
12115 } else if ((isa<StringLiteral>(RHSStripped) ||
12116 isa<ObjCEncodeExpr>(RHSStripped)) &&
12117 !LHSStripped->isNullPointerConstant(S.Context,
12118 Expr::NPC_ValueDependentIsNull)) {
12119 LiteralString = RHS;
12120 LiteralStringStripped = RHSStripped;
12123 if (LiteralString) {
12124 S.DiagRuntimeBehavior(Loc, nullptr,
12125 S.PDiag(diag::warn_stringcompare)
12126 << isa<ObjCEncodeExpr>(LiteralStringStripped)
12127 << LiteralString->getSourceRange());
12131 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
12132 switch (CK) {
12133 default: {
12134 #ifndef NDEBUG
12135 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12136 << "\n";
12137 #endif
12138 llvm_unreachable("unhandled cast kind");
12140 case CK_UserDefinedConversion:
12141 return ICK_Identity;
12142 case CK_LValueToRValue:
12143 return ICK_Lvalue_To_Rvalue;
12144 case CK_ArrayToPointerDecay:
12145 return ICK_Array_To_Pointer;
12146 case CK_FunctionToPointerDecay:
12147 return ICK_Function_To_Pointer;
12148 case CK_IntegralCast:
12149 return ICK_Integral_Conversion;
12150 case CK_FloatingCast:
12151 return ICK_Floating_Conversion;
12152 case CK_IntegralToFloating:
12153 case CK_FloatingToIntegral:
12154 return ICK_Floating_Integral;
12155 case CK_IntegralComplexCast:
12156 case CK_FloatingComplexCast:
12157 case CK_FloatingComplexToIntegralComplex:
12158 case CK_IntegralComplexToFloatingComplex:
12159 return ICK_Complex_Conversion;
12160 case CK_FloatingComplexToReal:
12161 case CK_FloatingRealToComplex:
12162 case CK_IntegralComplexToReal:
12163 case CK_IntegralRealToComplex:
12164 return ICK_Complex_Real;
12168 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12169 QualType FromType,
12170 SourceLocation Loc) {
12171 // Check for a narrowing implicit conversion.
12172 StandardConversionSequence SCS;
12173 SCS.setAsIdentityConversion();
12174 SCS.setToType(0, FromType);
12175 SCS.setToType(1, ToType);
12176 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12177 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12179 APValue PreNarrowingValue;
12180 QualType PreNarrowingType;
12181 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12182 PreNarrowingType,
12183 /*IgnoreFloatToIntegralConversion*/ true)) {
12184 case NK_Dependent_Narrowing:
12185 // Implicit conversion to a narrower type, but the expression is
12186 // value-dependent so we can't tell whether it's actually narrowing.
12187 case NK_Not_Narrowing:
12188 return false;
12190 case NK_Constant_Narrowing:
12191 // Implicit conversion to a narrower type, and the value is not a constant
12192 // expression.
12193 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12194 << /*Constant*/ 1
12195 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12196 return true;
12198 case NK_Variable_Narrowing:
12199 // Implicit conversion to a narrower type, and the value is not a constant
12200 // expression.
12201 case NK_Type_Narrowing:
12202 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12203 << /*Constant*/ 0 << FromType << ToType;
12204 // TODO: It's not a constant expression, but what if the user intended it
12205 // to be? Can we produce notes to help them figure out why it isn't?
12206 return true;
12208 llvm_unreachable("unhandled case in switch");
12211 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
12212 ExprResult &LHS,
12213 ExprResult &RHS,
12214 SourceLocation Loc) {
12215 QualType LHSType = LHS.get()->getType();
12216 QualType RHSType = RHS.get()->getType();
12217 // Dig out the original argument type and expression before implicit casts
12218 // were applied. These are the types/expressions we need to check the
12219 // [expr.spaceship] requirements against.
12220 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12221 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12222 QualType LHSStrippedType = LHSStripped.get()->getType();
12223 QualType RHSStrippedType = RHSStripped.get()->getType();
12225 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12226 // other is not, the program is ill-formed.
12227 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12228 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12229 return QualType();
12232 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12233 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12234 RHSStrippedType->isEnumeralType();
12235 if (NumEnumArgs == 1) {
12236 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12237 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12238 if (OtherTy->hasFloatingRepresentation()) {
12239 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12240 return QualType();
12243 if (NumEnumArgs == 2) {
12244 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12245 // type E, the operator yields the result of converting the operands
12246 // to the underlying type of E and applying <=> to the converted operands.
12247 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12248 S.InvalidOperands(Loc, LHS, RHS);
12249 return QualType();
12251 QualType IntType =
12252 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
12253 assert(IntType->isArithmeticType());
12255 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12256 // promote the boolean type, and all other promotable integer types, to
12257 // avoid this.
12258 if (IntType->isPromotableIntegerType())
12259 IntType = S.Context.getPromotedIntegerType(IntType);
12261 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12262 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12263 LHSType = RHSType = IntType;
12266 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12267 // usual arithmetic conversions are applied to the operands.
12268 QualType Type =
12269 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12270 if (LHS.isInvalid() || RHS.isInvalid())
12271 return QualType();
12272 if (Type.isNull())
12273 return S.InvalidOperands(Loc, LHS, RHS);
12275 Optional<ComparisonCategoryType> CCT =
12276 getComparisonCategoryForBuiltinCmp(Type);
12277 if (!CCT)
12278 return S.InvalidOperands(Loc, LHS, RHS);
12280 bool HasNarrowing = checkThreeWayNarrowingConversion(
12281 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12282 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12283 RHS.get()->getBeginLoc());
12284 if (HasNarrowing)
12285 return QualType();
12287 assert(!Type.isNull() && "composite type for <=> has not been set");
12289 return S.CheckComparisonCategoryType(
12290 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
12293 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
12294 ExprResult &RHS,
12295 SourceLocation Loc,
12296 BinaryOperatorKind Opc) {
12297 if (Opc == BO_Cmp)
12298 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12300 // C99 6.5.8p3 / C99 6.5.9p4
12301 QualType Type =
12302 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12303 if (LHS.isInvalid() || RHS.isInvalid())
12304 return QualType();
12305 if (Type.isNull())
12306 return S.InvalidOperands(Loc, LHS, RHS);
12307 assert(Type->isArithmeticType() || Type->isEnumeralType());
12309 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
12310 return S.InvalidOperands(Loc, LHS, RHS);
12312 // Check for comparisons of floating point operands using != and ==.
12313 if (Type->hasFloatingRepresentation())
12314 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12316 // The result of comparisons is 'bool' in C++, 'int' in C.
12317 return S.Context.getLogicalOperationType();
12320 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
12321 if (!NullE.get()->getType()->isAnyPointerType())
12322 return;
12323 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12324 if (!E.get()->getType()->isAnyPointerType() &&
12325 E.get()->isNullPointerConstant(Context,
12326 Expr::NPC_ValueDependentIsNotNull) ==
12327 Expr::NPCK_ZeroExpression) {
12328 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12329 if (CL->getValue() == 0)
12330 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12331 << NullValue
12332 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12333 NullValue ? "NULL" : "(void *)0");
12334 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12335 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12336 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
12337 if (T == Context.CharTy)
12338 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12339 << NullValue
12340 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12341 NullValue ? "NULL" : "(void *)0");
12346 // C99 6.5.8, C++ [expr.rel]
12347 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
12348 SourceLocation Loc,
12349 BinaryOperatorKind Opc) {
12350 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12351 bool IsThreeWay = Opc == BO_Cmp;
12352 bool IsOrdered = IsRelational || IsThreeWay;
12353 auto IsAnyPointerType = [](ExprResult E) {
12354 QualType Ty = E.get()->getType();
12355 return Ty->isPointerType() || Ty->isMemberPointerType();
12358 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12359 // type, array-to-pointer, ..., conversions are performed on both operands to
12360 // bring them to their composite type.
12361 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12362 // any type-related checks.
12363 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12364 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12365 if (LHS.isInvalid())
12366 return QualType();
12367 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12368 if (RHS.isInvalid())
12369 return QualType();
12370 } else {
12371 LHS = DefaultLvalueConversion(LHS.get());
12372 if (LHS.isInvalid())
12373 return QualType();
12374 RHS = DefaultLvalueConversion(RHS.get());
12375 if (RHS.isInvalid())
12376 return QualType();
12379 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12380 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
12381 CheckPtrComparisonWithNullChar(LHS, RHS);
12382 CheckPtrComparisonWithNullChar(RHS, LHS);
12385 // Handle vector comparisons separately.
12386 if (LHS.get()->getType()->isVectorType() ||
12387 RHS.get()->getType()->isVectorType())
12388 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12390 if (LHS.get()->getType()->isVLSTBuiltinType() ||
12391 RHS.get()->getType()->isVLSTBuiltinType())
12392 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12394 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12395 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12397 QualType LHSType = LHS.get()->getType();
12398 QualType RHSType = RHS.get()->getType();
12399 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12400 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12401 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12403 const Expr::NullPointerConstantKind LHSNullKind =
12404 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12405 const Expr::NullPointerConstantKind RHSNullKind =
12406 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12407 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12408 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12410 auto computeResultTy = [&]() {
12411 if (Opc != BO_Cmp)
12412 return Context.getLogicalOperationType();
12413 assert(getLangOpts().CPlusPlus);
12414 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12416 QualType CompositeTy = LHS.get()->getType();
12417 assert(!CompositeTy->isReferenceType());
12419 Optional<ComparisonCategoryType> CCT =
12420 getComparisonCategoryForBuiltinCmp(CompositeTy);
12421 if (!CCT)
12422 return InvalidOperands(Loc, LHS, RHS);
12424 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12425 // P0946R0: Comparisons between a null pointer constant and an object
12426 // pointer result in std::strong_equality, which is ill-formed under
12427 // P1959R0.
12428 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12429 << (LHSIsNull ? LHS.get()->getSourceRange()
12430 : RHS.get()->getSourceRange());
12431 return QualType();
12434 return CheckComparisonCategoryType(
12435 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
12438 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12439 bool IsEquality = Opc == BO_EQ;
12440 if (RHSIsNull)
12441 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12442 RHS.get()->getSourceRange());
12443 else
12444 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12445 LHS.get()->getSourceRange());
12448 if (IsOrdered && LHSType->isFunctionPointerType() &&
12449 RHSType->isFunctionPointerType()) {
12450 // Valid unless a relational comparison of function pointers
12451 bool IsError = Opc == BO_Cmp;
12452 auto DiagID =
12453 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12454 : getLangOpts().CPlusPlus
12455 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12456 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12457 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12458 << RHS.get()->getSourceRange();
12459 if (IsError)
12460 return QualType();
12463 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12464 (RHSType->isIntegerType() && !RHSIsNull)) {
12465 // Skip normal pointer conversion checks in this case; we have better
12466 // diagnostics for this below.
12467 } else if (getLangOpts().CPlusPlus) {
12468 // Equality comparison of a function pointer to a void pointer is invalid,
12469 // but we allow it as an extension.
12470 // FIXME: If we really want to allow this, should it be part of composite
12471 // pointer type computation so it works in conditionals too?
12472 if (!IsOrdered &&
12473 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12474 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12475 // This is a gcc extension compatibility comparison.
12476 // In a SFINAE context, we treat this as a hard error to maintain
12477 // conformance with the C++ standard.
12478 diagnoseFunctionPointerToVoidComparison(
12479 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12481 if (isSFINAEContext())
12482 return QualType();
12484 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12485 return computeResultTy();
12488 // C++ [expr.eq]p2:
12489 // If at least one operand is a pointer [...] bring them to their
12490 // composite pointer type.
12491 // C++ [expr.spaceship]p6
12492 // If at least one of the operands is of pointer type, [...] bring them
12493 // to their composite pointer type.
12494 // C++ [expr.rel]p2:
12495 // If both operands are pointers, [...] bring them to their composite
12496 // pointer type.
12497 // For <=>, the only valid non-pointer types are arrays and functions, and
12498 // we already decayed those, so this is really the same as the relational
12499 // comparison rule.
12500 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12501 (IsOrdered ? 2 : 1) &&
12502 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12503 RHSType->isObjCObjectPointerType()))) {
12504 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12505 return QualType();
12506 return computeResultTy();
12508 } else if (LHSType->isPointerType() &&
12509 RHSType->isPointerType()) { // C99 6.5.8p2
12510 // All of the following pointer-related warnings are GCC extensions, except
12511 // when handling null pointer constants.
12512 QualType LCanPointeeTy =
12513 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12514 QualType RCanPointeeTy =
12515 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12517 // C99 6.5.9p2 and C99 6.5.8p2
12518 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12519 RCanPointeeTy.getUnqualifiedType())) {
12520 if (IsRelational) {
12521 // Pointers both need to point to complete or incomplete types
12522 if ((LCanPointeeTy->isIncompleteType() !=
12523 RCanPointeeTy->isIncompleteType()) &&
12524 !getLangOpts().C11) {
12525 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12526 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12527 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12528 << RCanPointeeTy->isIncompleteType();
12531 } else if (!IsRelational &&
12532 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12533 // Valid unless comparison between non-null pointer and function pointer
12534 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12535 && !LHSIsNull && !RHSIsNull)
12536 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
12537 /*isError*/false);
12538 } else {
12539 // Invalid
12540 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12542 if (LCanPointeeTy != RCanPointeeTy) {
12543 // Treat NULL constant as a special case in OpenCL.
12544 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12545 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
12546 Diag(Loc,
12547 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12548 << LHSType << RHSType << 0 /* comparison */
12549 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12552 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12553 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12554 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12555 : CK_BitCast;
12556 if (LHSIsNull && !RHSIsNull)
12557 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12558 else
12559 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12561 return computeResultTy();
12564 if (getLangOpts().CPlusPlus) {
12565 // C++ [expr.eq]p4:
12566 // Two operands of type std::nullptr_t or one operand of type
12567 // std::nullptr_t and the other a null pointer constant compare equal.
12568 if (!IsOrdered && LHSIsNull && RHSIsNull) {
12569 if (LHSType->isNullPtrType()) {
12570 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12571 return computeResultTy();
12573 if (RHSType->isNullPtrType()) {
12574 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12575 return computeResultTy();
12579 // Comparison of Objective-C pointers and block pointers against nullptr_t.
12580 // These aren't covered by the composite pointer type rules.
12581 if (!IsOrdered && RHSType->isNullPtrType() &&
12582 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12583 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12584 return computeResultTy();
12586 if (!IsOrdered && LHSType->isNullPtrType() &&
12587 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12588 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12589 return computeResultTy();
12592 if (IsRelational &&
12593 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12594 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12595 // HACK: Relational comparison of nullptr_t against a pointer type is
12596 // invalid per DR583, but we allow it within std::less<> and friends,
12597 // since otherwise common uses of it break.
12598 // FIXME: Consider removing this hack once LWG fixes std::less<> and
12599 // friends to have std::nullptr_t overload candidates.
12600 DeclContext *DC = CurContext;
12601 if (isa<FunctionDecl>(DC))
12602 DC = DC->getParent();
12603 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12604 if (CTSD->isInStdNamespace() &&
12605 llvm::StringSwitch<bool>(CTSD->getName())
12606 .Cases("less", "less_equal", "greater", "greater_equal", true)
12607 .Default(false)) {
12608 if (RHSType->isNullPtrType())
12609 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12610 else
12611 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12612 return computeResultTy();
12617 // C++ [expr.eq]p2:
12618 // If at least one operand is a pointer to member, [...] bring them to
12619 // their composite pointer type.
12620 if (!IsOrdered &&
12621 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12622 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12623 return QualType();
12624 else
12625 return computeResultTy();
12629 // Handle block pointer types.
12630 if (!IsOrdered && LHSType->isBlockPointerType() &&
12631 RHSType->isBlockPointerType()) {
12632 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12633 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12635 if (!LHSIsNull && !RHSIsNull &&
12636 !Context.typesAreCompatible(lpointee, rpointee)) {
12637 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12638 << LHSType << RHSType << LHS.get()->getSourceRange()
12639 << RHS.get()->getSourceRange();
12641 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12642 return computeResultTy();
12645 // Allow block pointers to be compared with null pointer constants.
12646 if (!IsOrdered
12647 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12648 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12649 if (!LHSIsNull && !RHSIsNull) {
12650 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12651 ->getPointeeType()->isVoidType())
12652 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12653 ->getPointeeType()->isVoidType())))
12654 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12655 << LHSType << RHSType << LHS.get()->getSourceRange()
12656 << RHS.get()->getSourceRange();
12658 if (LHSIsNull && !RHSIsNull)
12659 LHS = ImpCastExprToType(LHS.get(), RHSType,
12660 RHSType->isPointerType() ? CK_BitCast
12661 : CK_AnyPointerToBlockPointerCast);
12662 else
12663 RHS = ImpCastExprToType(RHS.get(), LHSType,
12664 LHSType->isPointerType() ? CK_BitCast
12665 : CK_AnyPointerToBlockPointerCast);
12666 return computeResultTy();
12669 if (LHSType->isObjCObjectPointerType() ||
12670 RHSType->isObjCObjectPointerType()) {
12671 const PointerType *LPT = LHSType->getAs<PointerType>();
12672 const PointerType *RPT = RHSType->getAs<PointerType>();
12673 if (LPT || RPT) {
12674 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12675 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12677 if (!LPtrToVoid && !RPtrToVoid &&
12678 !Context.typesAreCompatible(LHSType, RHSType)) {
12679 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12680 /*isError*/false);
12682 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12683 // the RHS, but we have test coverage for this behavior.
12684 // FIXME: Consider using convertPointersToCompositeType in C++.
12685 if (LHSIsNull && !RHSIsNull) {
12686 Expr *E = LHS.get();
12687 if (getLangOpts().ObjCAutoRefCount)
12688 CheckObjCConversion(SourceRange(), RHSType, E,
12689 CCK_ImplicitConversion);
12690 LHS = ImpCastExprToType(E, RHSType,
12691 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12693 else {
12694 Expr *E = RHS.get();
12695 if (getLangOpts().ObjCAutoRefCount)
12696 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
12697 /*Diagnose=*/true,
12698 /*DiagnoseCFAudited=*/false, Opc);
12699 RHS = ImpCastExprToType(E, LHSType,
12700 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12702 return computeResultTy();
12704 if (LHSType->isObjCObjectPointerType() &&
12705 RHSType->isObjCObjectPointerType()) {
12706 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12707 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12708 /*isError*/false);
12709 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
12710 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12712 if (LHSIsNull && !RHSIsNull)
12713 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12714 else
12715 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12716 return computeResultTy();
12719 if (!IsOrdered && LHSType->isBlockPointerType() &&
12720 RHSType->isBlockCompatibleObjCPointerType(Context)) {
12721 LHS = ImpCastExprToType(LHS.get(), RHSType,
12722 CK_BlockPointerToObjCPointerCast);
12723 return computeResultTy();
12724 } else if (!IsOrdered &&
12725 LHSType->isBlockCompatibleObjCPointerType(Context) &&
12726 RHSType->isBlockPointerType()) {
12727 RHS = ImpCastExprToType(RHS.get(), LHSType,
12728 CK_BlockPointerToObjCPointerCast);
12729 return computeResultTy();
12732 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12733 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12734 unsigned DiagID = 0;
12735 bool isError = false;
12736 if (LangOpts.DebuggerSupport) {
12737 // Under a debugger, allow the comparison of pointers to integers,
12738 // since users tend to want to compare addresses.
12739 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12740 (RHSIsNull && RHSType->isIntegerType())) {
12741 if (IsOrdered) {
12742 isError = getLangOpts().CPlusPlus;
12743 DiagID =
12744 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12745 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12747 } else if (getLangOpts().CPlusPlus) {
12748 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12749 isError = true;
12750 } else if (IsOrdered)
12751 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12752 else
12753 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12755 if (DiagID) {
12756 Diag(Loc, DiagID)
12757 << LHSType << RHSType << LHS.get()->getSourceRange()
12758 << RHS.get()->getSourceRange();
12759 if (isError)
12760 return QualType();
12763 if (LHSType->isIntegerType())
12764 LHS = ImpCastExprToType(LHS.get(), RHSType,
12765 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12766 else
12767 RHS = ImpCastExprToType(RHS.get(), LHSType,
12768 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12769 return computeResultTy();
12772 // Handle block pointers.
12773 if (!IsOrdered && RHSIsNull
12774 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12775 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12776 return computeResultTy();
12778 if (!IsOrdered && LHSIsNull
12779 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12780 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12781 return computeResultTy();
12784 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12785 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12786 return computeResultTy();
12789 if (LHSType->isQueueT() && RHSType->isQueueT()) {
12790 return computeResultTy();
12793 if (LHSIsNull && RHSType->isQueueT()) {
12794 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12795 return computeResultTy();
12798 if (LHSType->isQueueT() && RHSIsNull) {
12799 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12800 return computeResultTy();
12804 return InvalidOperands(Loc, LHS, RHS);
12807 // Return a signed ext_vector_type that is of identical size and number of
12808 // elements. For floating point vectors, return an integer type of identical
12809 // size and number of elements. In the non ext_vector_type case, search from
12810 // the largest type to the smallest type to avoid cases where long long == long,
12811 // where long gets picked over long long.
12812 QualType Sema::GetSignedVectorType(QualType V) {
12813 const VectorType *VTy = V->castAs<VectorType>();
12814 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12816 if (isa<ExtVectorType>(VTy)) {
12817 if (VTy->isExtVectorBoolType())
12818 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
12819 if (TypeSize == Context.getTypeSize(Context.CharTy))
12820 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
12821 if (TypeSize == Context.getTypeSize(Context.ShortTy))
12822 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
12823 if (TypeSize == Context.getTypeSize(Context.IntTy))
12824 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
12825 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12826 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
12827 if (TypeSize == Context.getTypeSize(Context.LongTy))
12828 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
12829 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12830 "Unhandled vector element size in vector compare");
12831 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
12834 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12835 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
12836 VectorType::GenericVector);
12837 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12838 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
12839 VectorType::GenericVector);
12840 if (TypeSize == Context.getTypeSize(Context.LongTy))
12841 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
12842 VectorType::GenericVector);
12843 if (TypeSize == Context.getTypeSize(Context.IntTy))
12844 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
12845 VectorType::GenericVector);
12846 if (TypeSize == Context.getTypeSize(Context.ShortTy))
12847 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
12848 VectorType::GenericVector);
12849 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12850 "Unhandled vector element size in vector compare");
12851 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
12852 VectorType::GenericVector);
12855 QualType Sema::GetSignedSizelessVectorType(QualType V) {
12856 const BuiltinType *VTy = V->castAs<BuiltinType>();
12857 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
12859 const QualType ETy = V->getSveEltType(Context);
12860 const auto TypeSize = Context.getTypeSize(ETy);
12862 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
12863 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
12864 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
12867 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
12868 /// operates on extended vector types. Instead of producing an IntTy result,
12869 /// like a scalar comparison, a vector comparison produces a vector of integer
12870 /// types.
12871 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12872 SourceLocation Loc,
12873 BinaryOperatorKind Opc) {
12874 if (Opc == BO_Cmp) {
12875 Diag(Loc, diag::err_three_way_vector_comparison);
12876 return QualType();
12879 // Check to make sure we're operating on vectors of the same type and width,
12880 // Allowing one side to be a scalar of element type.
12881 QualType vType =
12882 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
12883 /*AllowBothBool*/ true,
12884 /*AllowBoolConversions*/ getLangOpts().ZVector,
12885 /*AllowBooleanOperation*/ true,
12886 /*ReportInvalid*/ true);
12887 if (vType.isNull())
12888 return vType;
12890 QualType LHSType = LHS.get()->getType();
12892 // Determine the return type of a vector compare. By default clang will return
12893 // a scalar for all vector compares except vector bool and vector pixel.
12894 // With the gcc compiler we will always return a vector type and with the xl
12895 // compiler we will always return a scalar type. This switch allows choosing
12896 // which behavior is prefered.
12897 if (getLangOpts().AltiVec) {
12898 switch (getLangOpts().getAltivecSrcCompat()) {
12899 case LangOptions::AltivecSrcCompatKind::Mixed:
12900 // If AltiVec, the comparison results in a numeric type, i.e.
12901 // bool for C++, int for C
12902 if (vType->castAs<VectorType>()->getVectorKind() ==
12903 VectorType::AltiVecVector)
12904 return Context.getLogicalOperationType();
12905 else
12906 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12907 break;
12908 case LangOptions::AltivecSrcCompatKind::GCC:
12909 // For GCC we always return the vector type.
12910 break;
12911 case LangOptions::AltivecSrcCompatKind::XL:
12912 return Context.getLogicalOperationType();
12913 break;
12917 // For non-floating point types, check for self-comparisons of the form
12918 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12919 // often indicate logic errors in the program.
12920 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12922 // Check for comparisons of floating point operands using != and ==.
12923 if (LHSType->hasFloatingRepresentation()) {
12924 assert(RHS.get()->getType()->hasFloatingRepresentation());
12925 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12928 // Return a signed type for the vector.
12929 return GetSignedVectorType(vType);
12932 QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
12933 ExprResult &RHS,
12934 SourceLocation Loc,
12935 BinaryOperatorKind Opc) {
12936 if (Opc == BO_Cmp) {
12937 Diag(Loc, diag::err_three_way_vector_comparison);
12938 return QualType();
12941 // Check to make sure we're operating on vectors of the same type and width,
12942 // Allowing one side to be a scalar of element type.
12943 QualType vType = CheckSizelessVectorOperands(
12944 LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
12946 if (vType.isNull())
12947 return vType;
12949 QualType LHSType = LHS.get()->getType();
12951 // For non-floating point types, check for self-comparisons of the form
12952 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12953 // often indicate logic errors in the program.
12954 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12956 // Check for comparisons of floating point operands using != and ==.
12957 if (LHSType->hasFloatingRepresentation()) {
12958 assert(RHS.get()->getType()->hasFloatingRepresentation());
12959 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12962 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
12963 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
12965 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
12966 RHSBuiltinTy->isSVEBool())
12967 return LHSType;
12969 // Return a signed type for the vector.
12970 return GetSignedSizelessVectorType(vType);
12973 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12974 const ExprResult &XorRHS,
12975 const SourceLocation Loc) {
12976 // Do not diagnose macros.
12977 if (Loc.isMacroID())
12978 return;
12980 // Do not diagnose if both LHS and RHS are macros.
12981 if (XorLHS.get()->getExprLoc().isMacroID() &&
12982 XorRHS.get()->getExprLoc().isMacroID())
12983 return;
12985 bool Negative = false;
12986 bool ExplicitPlus = false;
12987 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12988 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12990 if (!LHSInt)
12991 return;
12992 if (!RHSInt) {
12993 // Check negative literals.
12994 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12995 UnaryOperatorKind Opc = UO->getOpcode();
12996 if (Opc != UO_Minus && Opc != UO_Plus)
12997 return;
12998 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12999 if (!RHSInt)
13000 return;
13001 Negative = (Opc == UO_Minus);
13002 ExplicitPlus = !Negative;
13003 } else {
13004 return;
13008 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13009 llvm::APInt RightSideValue = RHSInt->getValue();
13010 if (LeftSideValue != 2 && LeftSideValue != 10)
13011 return;
13013 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13014 return;
13016 CharSourceRange ExprRange = CharSourceRange::getCharRange(
13017 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
13018 llvm::StringRef ExprStr =
13019 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
13021 CharSourceRange XorRange =
13022 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
13023 llvm::StringRef XorStr =
13024 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
13025 // Do not diagnose if xor keyword/macro is used.
13026 if (XorStr == "xor")
13027 return;
13029 std::string LHSStr = std::string(Lexer::getSourceText(
13030 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13031 S.getSourceManager(), S.getLangOpts()));
13032 std::string RHSStr = std::string(Lexer::getSourceText(
13033 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13034 S.getSourceManager(), S.getLangOpts()));
13036 if (Negative) {
13037 RightSideValue = -RightSideValue;
13038 RHSStr = "-" + RHSStr;
13039 } else if (ExplicitPlus) {
13040 RHSStr = "+" + RHSStr;
13043 StringRef LHSStrRef = LHSStr;
13044 StringRef RHSStrRef = RHSStr;
13045 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13046 // literals.
13047 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
13048 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
13049 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
13050 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
13051 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
13052 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
13053 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13054 return;
13056 bool SuggestXor =
13057 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13058 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13059 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13060 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13061 std::string SuggestedExpr = "1 << " + RHSStr;
13062 bool Overflow = false;
13063 llvm::APInt One = (LeftSideValue - 1);
13064 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13065 if (Overflow) {
13066 if (RightSideIntValue < 64)
13067 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13068 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13069 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13070 else if (RightSideIntValue == 64)
13071 S.Diag(Loc, diag::warn_xor_used_as_pow)
13072 << ExprStr << toString(XorValue, 10, true);
13073 else
13074 return;
13075 } else {
13076 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13077 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13078 << toString(PowValue, 10, true)
13079 << FixItHint::CreateReplacement(
13080 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13083 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13084 << ("0x2 ^ " + RHSStr) << SuggestXor;
13085 } else if (LeftSideValue == 10) {
13086 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13087 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13088 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13089 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13090 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13091 << ("0xA ^ " + RHSStr) << SuggestXor;
13095 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13096 SourceLocation Loc) {
13097 // Ensure that either both operands are of the same vector type, or
13098 // one operand is of a vector type and the other is of its element type.
13099 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13100 /*AllowBothBool*/ true,
13101 /*AllowBoolConversions*/ false,
13102 /*AllowBooleanOperation*/ false,
13103 /*ReportInvalid*/ false);
13104 if (vType.isNull())
13105 return InvalidOperands(Loc, LHS, RHS);
13106 if (getLangOpts().OpenCL &&
13107 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13108 vType->hasFloatingRepresentation())
13109 return InvalidOperands(Loc, LHS, RHS);
13110 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13111 // usage of the logical operators && and || with vectors in C. This
13112 // check could be notionally dropped.
13113 if (!getLangOpts().CPlusPlus &&
13114 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13115 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13117 return GetSignedVectorType(LHS.get()->getType());
13120 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
13121 SourceLocation Loc,
13122 bool IsCompAssign) {
13123 if (!IsCompAssign) {
13124 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13125 if (LHS.isInvalid())
13126 return QualType();
13128 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13129 if (RHS.isInvalid())
13130 return QualType();
13132 // For conversion purposes, we ignore any qualifiers.
13133 // For example, "const float" and "float" are equivalent.
13134 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13135 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13137 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13138 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13139 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13141 if (Context.hasSameType(LHSType, RHSType))
13142 return Context.getCommonSugaredType(LHSType, RHSType);
13144 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13145 // case we have to return InvalidOperands.
13146 ExprResult OriginalLHS = LHS;
13147 ExprResult OriginalRHS = RHS;
13148 if (LHSMatType && !RHSMatType) {
13149 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13150 if (!RHS.isInvalid())
13151 return LHSType;
13153 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13156 if (!LHSMatType && RHSMatType) {
13157 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13158 if (!LHS.isInvalid())
13159 return RHSType;
13160 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13163 return InvalidOperands(Loc, LHS, RHS);
13166 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
13167 SourceLocation Loc,
13168 bool IsCompAssign) {
13169 if (!IsCompAssign) {
13170 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13171 if (LHS.isInvalid())
13172 return QualType();
13174 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13175 if (RHS.isInvalid())
13176 return QualType();
13178 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13179 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13180 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13182 if (LHSMatType && RHSMatType) {
13183 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13184 return InvalidOperands(Loc, LHS, RHS);
13186 if (Context.hasSameType(LHSMatType, RHSMatType))
13187 return Context.getCommonSugaredType(
13188 LHS.get()->getType().getUnqualifiedType(),
13189 RHS.get()->getType().getUnqualifiedType());
13191 QualType LHSELTy = LHSMatType->getElementType(),
13192 RHSELTy = RHSMatType->getElementType();
13193 if (!Context.hasSameType(LHSELTy, RHSELTy))
13194 return InvalidOperands(Loc, LHS, RHS);
13196 return Context.getConstantMatrixType(
13197 Context.getCommonSugaredType(LHSELTy, RHSELTy),
13198 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13200 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13203 static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
13204 switch (Opc) {
13205 default:
13206 return false;
13207 case BO_And:
13208 case BO_AndAssign:
13209 case BO_Or:
13210 case BO_OrAssign:
13211 case BO_Xor:
13212 case BO_XorAssign:
13213 return true;
13217 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
13218 SourceLocation Loc,
13219 BinaryOperatorKind Opc) {
13220 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13222 bool IsCompAssign =
13223 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13225 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13227 if (LHS.get()->getType()->isVectorType() ||
13228 RHS.get()->getType()->isVectorType()) {
13229 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13230 RHS.get()->getType()->hasIntegerRepresentation())
13231 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13232 /*AllowBothBool*/ true,
13233 /*AllowBoolConversions*/ getLangOpts().ZVector,
13234 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13235 /*ReportInvalid*/ true);
13236 return InvalidOperands(Loc, LHS, RHS);
13239 if (LHS.get()->getType()->isVLSTBuiltinType() ||
13240 RHS.get()->getType()->isVLSTBuiltinType()) {
13241 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13242 RHS.get()->getType()->hasIntegerRepresentation())
13243 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13244 ACK_BitwiseOp);
13245 return InvalidOperands(Loc, LHS, RHS);
13248 if (LHS.get()->getType()->isVLSTBuiltinType() ||
13249 RHS.get()->getType()->isVLSTBuiltinType()) {
13250 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13251 RHS.get()->getType()->hasIntegerRepresentation())
13252 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13253 ACK_BitwiseOp);
13254 return InvalidOperands(Loc, LHS, RHS);
13257 if (Opc == BO_And)
13258 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13260 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13261 RHS.get()->getType()->hasFloatingRepresentation())
13262 return InvalidOperands(Loc, LHS, RHS);
13264 ExprResult LHSResult = LHS, RHSResult = RHS;
13265 QualType compType = UsualArithmeticConversions(
13266 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
13267 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13268 return QualType();
13269 LHS = LHSResult.get();
13270 RHS = RHSResult.get();
13272 if (Opc == BO_Xor)
13273 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13275 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13276 return compType;
13277 return InvalidOperands(Loc, LHS, RHS);
13280 // C99 6.5.[13,14]
13281 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13282 SourceLocation Loc,
13283 BinaryOperatorKind Opc) {
13284 // Check vector operands differently.
13285 if (LHS.get()->getType()->isVectorType() ||
13286 RHS.get()->getType()->isVectorType())
13287 return CheckVectorLogicalOperands(LHS, RHS, Loc);
13289 bool EnumConstantInBoolContext = false;
13290 for (const ExprResult &HS : {LHS, RHS}) {
13291 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13292 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13293 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13294 EnumConstantInBoolContext = true;
13298 if (EnumConstantInBoolContext)
13299 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13301 // Diagnose cases where the user write a logical and/or but probably meant a
13302 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13303 // is a constant.
13304 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13305 !LHS.get()->getType()->isBooleanType() &&
13306 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13307 // Don't warn in macros or template instantiations.
13308 !Loc.isMacroID() && !inTemplateInstantiation()) {
13309 // If the RHS can be constant folded, and if it constant folds to something
13310 // that isn't 0 or 1 (which indicate a potential logical operation that
13311 // happened to fold to true/false) then warn.
13312 // Parens on the RHS are ignored.
13313 Expr::EvalResult EVResult;
13314 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13315 llvm::APSInt Result = EVResult.Val.getInt();
13316 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
13317 !RHS.get()->getExprLoc().isMacroID()) ||
13318 (Result != 0 && Result != 1)) {
13319 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13320 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13321 // Suggest replacing the logical operator with the bitwise version
13322 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13323 << (Opc == BO_LAnd ? "&" : "|")
13324 << FixItHint::CreateReplacement(
13325 SourceRange(Loc, getLocForEndOfToken(Loc)),
13326 Opc == BO_LAnd ? "&" : "|");
13327 if (Opc == BO_LAnd)
13328 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13329 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13330 << FixItHint::CreateRemoval(
13331 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
13332 RHS.get()->getEndLoc()));
13337 if (!Context.getLangOpts().CPlusPlus) {
13338 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13339 // not operate on the built-in scalar and vector float types.
13340 if (Context.getLangOpts().OpenCL &&
13341 Context.getLangOpts().OpenCLVersion < 120) {
13342 if (LHS.get()->getType()->isFloatingType() ||
13343 RHS.get()->getType()->isFloatingType())
13344 return InvalidOperands(Loc, LHS, RHS);
13347 LHS = UsualUnaryConversions(LHS.get());
13348 if (LHS.isInvalid())
13349 return QualType();
13351 RHS = UsualUnaryConversions(RHS.get());
13352 if (RHS.isInvalid())
13353 return QualType();
13355 if (!LHS.get()->getType()->isScalarType() ||
13356 !RHS.get()->getType()->isScalarType())
13357 return InvalidOperands(Loc, LHS, RHS);
13359 return Context.IntTy;
13362 // The following is safe because we only use this method for
13363 // non-overloadable operands.
13365 // C++ [expr.log.and]p1
13366 // C++ [expr.log.or]p1
13367 // The operands are both contextually converted to type bool.
13368 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
13369 if (LHSRes.isInvalid())
13370 return InvalidOperands(Loc, LHS, RHS);
13371 LHS = LHSRes;
13373 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
13374 if (RHSRes.isInvalid())
13375 return InvalidOperands(Loc, LHS, RHS);
13376 RHS = RHSRes;
13378 // C++ [expr.log.and]p2
13379 // C++ [expr.log.or]p2
13380 // The result is a bool.
13381 return Context.BoolTy;
13384 static bool IsReadonlyMessage(Expr *E, Sema &S) {
13385 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13386 if (!ME) return false;
13387 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13388 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13389 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
13390 if (!Base) return false;
13391 return Base->getMethodDecl() != nullptr;
13394 /// Is the given expression (which must be 'const') a reference to a
13395 /// variable which was originally non-const, but which has become
13396 /// 'const' due to being captured within a block?
13397 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
13398 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
13399 assert(E->isLValue() && E->getType().isConstQualified());
13400 E = E->IgnoreParens();
13402 // Must be a reference to a declaration from an enclosing scope.
13403 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13404 if (!DRE) return NCCK_None;
13405 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
13407 // The declaration must be a variable which is not declared 'const'.
13408 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
13409 if (!var) return NCCK_None;
13410 if (var->getType().isConstQualified()) return NCCK_None;
13411 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
13413 // Decide whether the first capture was for a block or a lambda.
13414 DeclContext *DC = S.CurContext, *Prev = nullptr;
13415 // Decide whether the first capture was for a block or a lambda.
13416 while (DC) {
13417 // For init-capture, it is possible that the variable belongs to the
13418 // template pattern of the current context.
13419 if (auto *FD = dyn_cast<FunctionDecl>(DC))
13420 if (var->isInitCapture() &&
13421 FD->getTemplateInstantiationPattern() == var->getDeclContext())
13422 break;
13423 if (DC == var->getDeclContext())
13424 break;
13425 Prev = DC;
13426 DC = DC->getParent();
13428 // Unless we have an init-capture, we've gone one step too far.
13429 if (!var->isInitCapture())
13430 DC = Prev;
13431 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13434 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13435 Ty = Ty.getNonReferenceType();
13436 if (IsDereference && Ty->isPointerType())
13437 Ty = Ty->getPointeeType();
13438 return !Ty.isConstQualified();
13441 // Update err_typecheck_assign_const and note_typecheck_assign_const
13442 // when this enum is changed.
13443 enum {
13444 ConstFunction,
13445 ConstVariable,
13446 ConstMember,
13447 ConstMethod,
13448 NestedConstMember,
13449 ConstUnknown, // Keep as last element
13452 /// Emit the "read-only variable not assignable" error and print notes to give
13453 /// more information about why the variable is not assignable, such as pointing
13454 /// to the declaration of a const variable, showing that a method is const, or
13455 /// that the function is returning a const reference.
13456 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13457 SourceLocation Loc) {
13458 SourceRange ExprRange = E->getSourceRange();
13460 // Only emit one error on the first const found. All other consts will emit
13461 // a note to the error.
13462 bool DiagnosticEmitted = false;
13464 // Track if the current expression is the result of a dereference, and if the
13465 // next checked expression is the result of a dereference.
13466 bool IsDereference = false;
13467 bool NextIsDereference = false;
13469 // Loop to process MemberExpr chains.
13470 while (true) {
13471 IsDereference = NextIsDereference;
13473 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
13474 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13475 NextIsDereference = ME->isArrow();
13476 const ValueDecl *VD = ME->getMemberDecl();
13477 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13478 // Mutable fields can be modified even if the class is const.
13479 if (Field->isMutable()) {
13480 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13481 break;
13484 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13485 if (!DiagnosticEmitted) {
13486 S.Diag(Loc, diag::err_typecheck_assign_const)
13487 << ExprRange << ConstMember << false /*static*/ << Field
13488 << Field->getType();
13489 DiagnosticEmitted = true;
13491 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13492 << ConstMember << false /*static*/ << Field << Field->getType()
13493 << Field->getSourceRange();
13495 E = ME->getBase();
13496 continue;
13497 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13498 if (VDecl->getType().isConstQualified()) {
13499 if (!DiagnosticEmitted) {
13500 S.Diag(Loc, diag::err_typecheck_assign_const)
13501 << ExprRange << ConstMember << true /*static*/ << VDecl
13502 << VDecl->getType();
13503 DiagnosticEmitted = true;
13505 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13506 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13507 << VDecl->getSourceRange();
13509 // Static fields do not inherit constness from parents.
13510 break;
13512 break; // End MemberExpr
13513 } else if (const ArraySubscriptExpr *ASE =
13514 dyn_cast<ArraySubscriptExpr>(E)) {
13515 E = ASE->getBase()->IgnoreParenImpCasts();
13516 continue;
13517 } else if (const ExtVectorElementExpr *EVE =
13518 dyn_cast<ExtVectorElementExpr>(E)) {
13519 E = EVE->getBase()->IgnoreParenImpCasts();
13520 continue;
13522 break;
13525 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13526 // Function calls
13527 const FunctionDecl *FD = CE->getDirectCallee();
13528 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13529 if (!DiagnosticEmitted) {
13530 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13531 << ConstFunction << FD;
13532 DiagnosticEmitted = true;
13534 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
13535 diag::note_typecheck_assign_const)
13536 << ConstFunction << FD << FD->getReturnType()
13537 << FD->getReturnTypeSourceRange();
13539 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13540 // Point to variable declaration.
13541 if (const ValueDecl *VD = DRE->getDecl()) {
13542 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13543 if (!DiagnosticEmitted) {
13544 S.Diag(Loc, diag::err_typecheck_assign_const)
13545 << ExprRange << ConstVariable << VD << VD->getType();
13546 DiagnosticEmitted = true;
13548 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13549 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13552 } else if (isa<CXXThisExpr>(E)) {
13553 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13554 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13555 if (MD->isConst()) {
13556 if (!DiagnosticEmitted) {
13557 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13558 << ConstMethod << MD;
13559 DiagnosticEmitted = true;
13561 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13562 << ConstMethod << MD << MD->getSourceRange();
13568 if (DiagnosticEmitted)
13569 return;
13571 // Can't determine a more specific message, so display the generic error.
13572 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13575 enum OriginalExprKind {
13576 OEK_Variable,
13577 OEK_Member,
13578 OEK_LValue
13581 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
13582 const RecordType *Ty,
13583 SourceLocation Loc, SourceRange Range,
13584 OriginalExprKind OEK,
13585 bool &DiagnosticEmitted) {
13586 std::vector<const RecordType *> RecordTypeList;
13587 RecordTypeList.push_back(Ty);
13588 unsigned NextToCheckIndex = 0;
13589 // We walk the record hierarchy breadth-first to ensure that we print
13590 // diagnostics in field nesting order.
13591 while (RecordTypeList.size() > NextToCheckIndex) {
13592 bool IsNested = NextToCheckIndex > 0;
13593 for (const FieldDecl *Field :
13594 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
13595 // First, check every field for constness.
13596 QualType FieldTy = Field->getType();
13597 if (FieldTy.isConstQualified()) {
13598 if (!DiagnosticEmitted) {
13599 S.Diag(Loc, diag::err_typecheck_assign_const)
13600 << Range << NestedConstMember << OEK << VD
13601 << IsNested << Field;
13602 DiagnosticEmitted = true;
13604 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13605 << NestedConstMember << IsNested << Field
13606 << FieldTy << Field->getSourceRange();
13609 // Then we append it to the list to check next in order.
13610 FieldTy = FieldTy.getCanonicalType();
13611 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
13612 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13613 RecordTypeList.push_back(FieldRecTy);
13616 ++NextToCheckIndex;
13620 /// Emit an error for the case where a record we are trying to assign to has a
13621 /// const-qualified field somewhere in its hierarchy.
13622 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
13623 SourceLocation Loc) {
13624 QualType Ty = E->getType();
13625 assert(Ty->isRecordType() && "lvalue was not record?");
13626 SourceRange Range = E->getSourceRange();
13627 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13628 bool DiagEmitted = false;
13630 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13631 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13632 Range, OEK_Member, DiagEmitted);
13633 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13634 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13635 Range, OEK_Variable, DiagEmitted);
13636 else
13637 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13638 Range, OEK_LValue, DiagEmitted);
13639 if (!DiagEmitted)
13640 DiagnoseConstAssignment(S, E, Loc);
13643 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
13644 /// emit an error and return true. If so, return false.
13645 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
13646 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13648 S.CheckShadowingDeclModification(E, Loc);
13650 SourceLocation OrigLoc = Loc;
13651 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
13652 &Loc);
13653 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13654 IsLV = Expr::MLV_InvalidMessageExpression;
13655 if (IsLV == Expr::MLV_Valid)
13656 return false;
13658 unsigned DiagID = 0;
13659 bool NeedType = false;
13660 switch (IsLV) { // C99 6.5.16p2
13661 case Expr::MLV_ConstQualified:
13662 // Use a specialized diagnostic when we're assigning to an object
13663 // from an enclosing function or block.
13664 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
13665 if (NCCK == NCCK_Block)
13666 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13667 else
13668 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13669 break;
13672 // In ARC, use some specialized diagnostics for occasions where we
13673 // infer 'const'. These are always pseudo-strong variables.
13674 if (S.getLangOpts().ObjCAutoRefCount) {
13675 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13676 if (declRef && isa<VarDecl>(declRef->getDecl())) {
13677 VarDecl *var = cast<VarDecl>(declRef->getDecl());
13679 // Use the normal diagnostic if it's pseudo-__strong but the
13680 // user actually wrote 'const'.
13681 if (var->isARCPseudoStrong() &&
13682 (!var->getTypeSourceInfo() ||
13683 !var->getTypeSourceInfo()->getType().isConstQualified())) {
13684 // There are three pseudo-strong cases:
13685 // - self
13686 ObjCMethodDecl *method = S.getCurMethodDecl();
13687 if (method && var == method->getSelfDecl()) {
13688 DiagID = method->isClassMethod()
13689 ? diag::err_typecheck_arc_assign_self_class_method
13690 : diag::err_typecheck_arc_assign_self;
13692 // - Objective-C externally_retained attribute.
13693 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13694 isa<ParmVarDecl>(var)) {
13695 DiagID = diag::err_typecheck_arc_assign_externally_retained;
13697 // - fast enumeration variables
13698 } else {
13699 DiagID = diag::err_typecheck_arr_assign_enumeration;
13702 SourceRange Assign;
13703 if (Loc != OrigLoc)
13704 Assign = SourceRange(OrigLoc, OrigLoc);
13705 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13706 // We need to preserve the AST regardless, so migration tool
13707 // can do its job.
13708 return false;
13713 // If none of the special cases above are triggered, then this is a
13714 // simple const assignment.
13715 if (DiagID == 0) {
13716 DiagnoseConstAssignment(S, E, Loc);
13717 return true;
13720 break;
13721 case Expr::MLV_ConstAddrSpace:
13722 DiagnoseConstAssignment(S, E, Loc);
13723 return true;
13724 case Expr::MLV_ConstQualifiedField:
13725 DiagnoseRecursiveConstFields(S, E, Loc);
13726 return true;
13727 case Expr::MLV_ArrayType:
13728 case Expr::MLV_ArrayTemporary:
13729 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13730 NeedType = true;
13731 break;
13732 case Expr::MLV_NotObjectType:
13733 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13734 NeedType = true;
13735 break;
13736 case Expr::MLV_LValueCast:
13737 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13738 break;
13739 case Expr::MLV_Valid:
13740 llvm_unreachable("did not take early return for MLV_Valid");
13741 case Expr::MLV_InvalidExpression:
13742 case Expr::MLV_MemberFunction:
13743 case Expr::MLV_ClassTemporary:
13744 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13745 break;
13746 case Expr::MLV_IncompleteType:
13747 case Expr::MLV_IncompleteVoidType:
13748 return S.RequireCompleteType(Loc, E->getType(),
13749 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13750 case Expr::MLV_DuplicateVectorComponents:
13751 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13752 break;
13753 case Expr::MLV_NoSetterProperty:
13754 llvm_unreachable("readonly properties should be processed differently");
13755 case Expr::MLV_InvalidMessageExpression:
13756 DiagID = diag::err_readonly_message_assignment;
13757 break;
13758 case Expr::MLV_SubObjCPropertySetting:
13759 DiagID = diag::err_no_subobject_property_setting;
13760 break;
13763 SourceRange Assign;
13764 if (Loc != OrigLoc)
13765 Assign = SourceRange(OrigLoc, OrigLoc);
13766 if (NeedType)
13767 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13768 else
13769 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13770 return true;
13773 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13774 SourceLocation Loc,
13775 Sema &Sema) {
13776 if (Sema.inTemplateInstantiation())
13777 return;
13778 if (Sema.isUnevaluatedContext())
13779 return;
13780 if (Loc.isInvalid() || Loc.isMacroID())
13781 return;
13782 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13783 return;
13785 // C / C++ fields
13786 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13787 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13788 if (ML && MR) {
13789 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13790 return;
13791 const ValueDecl *LHSDecl =
13792 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13793 const ValueDecl *RHSDecl =
13794 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13795 if (LHSDecl != RHSDecl)
13796 return;
13797 if (LHSDecl->getType().isVolatileQualified())
13798 return;
13799 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13800 if (RefTy->getPointeeType().isVolatileQualified())
13801 return;
13803 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13806 // Objective-C instance variables
13807 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13808 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13809 if (OL && OR && OL->getDecl() == OR->getDecl()) {
13810 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13811 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13812 if (RL && RR && RL->getDecl() == RR->getDecl())
13813 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13817 // C99 6.5.16.1
13818 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
13819 SourceLocation Loc,
13820 QualType CompoundType,
13821 BinaryOperatorKind Opc) {
13822 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
13824 // Verify that LHS is a modifiable lvalue, and emit error if not.
13825 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13826 return QualType();
13828 QualType LHSType = LHSExpr->getType();
13829 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13830 CompoundType;
13831 // OpenCL v1.2 s6.1.1.1 p2:
13832 // The half data type can only be used to declare a pointer to a buffer that
13833 // contains half values
13834 if (getLangOpts().OpenCL &&
13835 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13836 LHSType->isHalfType()) {
13837 Diag(Loc, diag::err_opencl_half_load_store) << 1
13838 << LHSType.getUnqualifiedType();
13839 return QualType();
13842 AssignConvertType ConvTy;
13843 if (CompoundType.isNull()) {
13844 Expr *RHSCheck = RHS.get();
13846 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13848 QualType LHSTy(LHSType);
13849 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13850 if (RHS.isInvalid())
13851 return QualType();
13852 // Special case of NSObject attributes on c-style pointer types.
13853 if (ConvTy == IncompatiblePointer &&
13854 ((Context.isObjCNSObjectType(LHSType) &&
13855 RHSType->isObjCObjectPointerType()) ||
13856 (Context.isObjCNSObjectType(RHSType) &&
13857 LHSType->isObjCObjectPointerType())))
13858 ConvTy = Compatible;
13860 if (ConvTy == Compatible &&
13861 LHSType->isObjCObjectType())
13862 Diag(Loc, diag::err_objc_object_assignment)
13863 << LHSType;
13865 // If the RHS is a unary plus or minus, check to see if they = and + are
13866 // right next to each other. If so, the user may have typo'd "x =+ 4"
13867 // instead of "x += 4".
13868 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13869 RHSCheck = ICE->getSubExpr();
13870 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13871 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13872 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13873 // Only if the two operators are exactly adjacent.
13874 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13875 // And there is a space or other character before the subexpr of the
13876 // unary +/-. We don't want to warn on "x=-1".
13877 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13878 UO->getSubExpr()->getBeginLoc().isFileID()) {
13879 Diag(Loc, diag::warn_not_compound_assign)
13880 << (UO->getOpcode() == UO_Plus ? "+" : "-")
13881 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13885 if (ConvTy == Compatible) {
13886 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13887 // Warn about retain cycles where a block captures the LHS, but
13888 // not if the LHS is a simple variable into which the block is
13889 // being stored...unless that variable can be captured by reference!
13890 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13891 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13892 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13893 checkRetainCycles(LHSExpr, RHS.get());
13896 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13897 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
13898 // It is safe to assign a weak reference into a strong variable.
13899 // Although this code can still have problems:
13900 // id x = self.weakProp;
13901 // id y = self.weakProp;
13902 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13903 // paths through the function. This should be revisited if
13904 // -Wrepeated-use-of-weak is made flow-sensitive.
13905 // For ObjCWeak only, we do not warn if the assign is to a non-weak
13906 // variable, which will be valid for the current autorelease scope.
13907 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13908 RHS.get()->getBeginLoc()))
13909 getCurFunction()->markSafeWeakUse(RHS.get());
13911 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13912 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13915 } else {
13916 // Compound assignment "x += y"
13917 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13920 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13921 RHS.get(), AA_Assigning))
13922 return QualType();
13924 CheckForNullPointerDereference(*this, LHSExpr);
13926 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13927 if (CompoundType.isNull()) {
13928 // C++2a [expr.ass]p5:
13929 // A simple-assignment whose left operand is of a volatile-qualified
13930 // type is deprecated unless the assignment is either a discarded-value
13931 // expression or an unevaluated operand
13932 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13933 } else {
13934 // C++20 [expr.ass]p6:
13935 // [Compound-assignment] expressions are deprecated if E1 has
13936 // volatile-qualified type and op is not one of the bitwise
13937 // operators |, &, ˆ.
13938 switch (Opc) {
13939 case BO_OrAssign:
13940 case BO_AndAssign:
13941 case BO_XorAssign:
13942 break;
13943 default:
13944 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
13949 // C11 6.5.16p3: The type of an assignment expression is the type of the
13950 // left operand would have after lvalue conversion.
13951 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
13952 // qualified type, the value has the unqualified version of the type of the
13953 // lvalue; additionally, if the lvalue has atomic type, the value has the
13954 // non-atomic version of the type of the lvalue.
13955 // C++ 5.17p1: the type of the assignment expression is that of its left
13956 // operand.
13957 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
13960 // Scenarios to ignore if expression E is:
13961 // 1. an explicit cast expression into void
13962 // 2. a function call expression that returns void
13963 static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
13964 E = E->IgnoreParens();
13966 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13967 if (CE->getCastKind() == CK_ToVoid) {
13968 return true;
13971 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13972 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13973 CE->getSubExpr()->getType()->isDependentType()) {
13974 return true;
13978 if (const auto *CE = dyn_cast<CallExpr>(E))
13979 return CE->getCallReturnType(Context)->isVoidType();
13980 return false;
13983 // Look for instances where it is likely the comma operator is confused with
13984 // another operator. There is an explicit list of acceptable expressions for
13985 // the left hand side of the comma operator, otherwise emit a warning.
13986 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
13987 // No warnings in macros
13988 if (Loc.isMacroID())
13989 return;
13991 // Don't warn in template instantiations.
13992 if (inTemplateInstantiation())
13993 return;
13995 // Scope isn't fine-grained enough to explicitly list the specific cases, so
13996 // instead, skip more than needed, then call back into here with the
13997 // CommaVisitor in SemaStmt.cpp.
13998 // The listed locations are the initialization and increment portions
13999 // of a for loop. The additional checks are on the condition of
14000 // if statements, do/while loops, and for loops.
14001 // Differences in scope flags for C89 mode requires the extra logic.
14002 const unsigned ForIncrementFlags =
14003 getLangOpts().C99 || getLangOpts().CPlusPlus
14004 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
14005 : Scope::ContinueScope | Scope::BreakScope;
14006 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
14007 const unsigned ScopeFlags = getCurScope()->getFlags();
14008 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
14009 (ScopeFlags & ForInitFlags) == ForInitFlags)
14010 return;
14012 // If there are multiple comma operators used together, get the RHS of the
14013 // of the comma operator as the LHS.
14014 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
14015 if (BO->getOpcode() != BO_Comma)
14016 break;
14017 LHS = BO->getRHS();
14020 // Only allow some expressions on LHS to not warn.
14021 if (IgnoreCommaOperand(LHS, Context))
14022 return;
14024 Diag(Loc, diag::warn_comma_operator);
14025 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14026 << LHS->getSourceRange()
14027 << FixItHint::CreateInsertion(LHS->getBeginLoc(),
14028 LangOpts.CPlusPlus ? "static_cast<void>("
14029 : "(void)(")
14030 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
14031 ")");
14034 // C99 6.5.17
14035 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
14036 SourceLocation Loc) {
14037 LHS = S.CheckPlaceholderExpr(LHS.get());
14038 RHS = S.CheckPlaceholderExpr(RHS.get());
14039 if (LHS.isInvalid() || RHS.isInvalid())
14040 return QualType();
14042 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14043 // operands, but not unary promotions.
14044 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14046 // So we treat the LHS as a ignored value, and in C++ we allow the
14047 // containing site to determine what should be done with the RHS.
14048 LHS = S.IgnoredValueConversions(LHS.get());
14049 if (LHS.isInvalid())
14050 return QualType();
14052 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14054 if (!S.getLangOpts().CPlusPlus) {
14055 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
14056 if (RHS.isInvalid())
14057 return QualType();
14058 if (!RHS.get()->getType()->isVoidType())
14059 S.RequireCompleteType(Loc, RHS.get()->getType(),
14060 diag::err_incomplete_type);
14063 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14064 S.DiagnoseCommaOperator(LHS.get(), Loc);
14066 return RHS.get()->getType();
14069 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14070 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14071 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
14072 ExprValueKind &VK,
14073 ExprObjectKind &OK,
14074 SourceLocation OpLoc,
14075 bool IsInc, bool IsPrefix) {
14076 if (Op->isTypeDependent())
14077 return S.Context.DependentTy;
14079 QualType ResType = Op->getType();
14080 // Atomic types can be used for increment / decrement where the non-atomic
14081 // versions can, so ignore the _Atomic() specifier for the purpose of
14082 // checking.
14083 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14084 ResType = ResAtomicType->getValueType();
14086 assert(!ResType.isNull() && "no type for increment/decrement expression");
14088 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14089 // Decrement of bool is not allowed.
14090 if (!IsInc) {
14091 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14092 return QualType();
14094 // Increment of bool sets it to true, but is deprecated.
14095 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14096 : diag::warn_increment_bool)
14097 << Op->getSourceRange();
14098 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14099 // Error on enum increments and decrements in C++ mode
14100 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14101 return QualType();
14102 } else if (ResType->isRealType()) {
14103 // OK!
14104 } else if (ResType->isPointerType()) {
14105 // C99 6.5.2.4p2, 6.5.6p2
14106 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14107 return QualType();
14108 } else if (ResType->isObjCObjectPointerType()) {
14109 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14110 // Otherwise, we just need a complete type.
14111 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14112 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14113 return QualType();
14114 } else if (ResType->isAnyComplexType()) {
14115 // C99 does not support ++/-- on complex types, we allow as an extension.
14116 S.Diag(OpLoc, diag::ext_integer_increment_complex)
14117 << ResType << Op->getSourceRange();
14118 } else if (ResType->isPlaceholderType()) {
14119 ExprResult PR = S.CheckPlaceholderExpr(Op);
14120 if (PR.isInvalid()) return QualType();
14121 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14122 IsInc, IsPrefix);
14123 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14124 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14125 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14126 (ResType->castAs<VectorType>()->getVectorKind() !=
14127 VectorType::AltiVecBool)) {
14128 // The z vector extensions allow ++ and -- for non-bool vectors.
14129 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
14130 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14131 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14132 } else {
14133 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14134 << ResType << int(IsInc) << Op->getSourceRange();
14135 return QualType();
14137 // At this point, we know we have a real, complex or pointer type.
14138 // Now make sure the operand is a modifiable lvalue.
14139 if (CheckForModifiableLvalue(Op, OpLoc, S))
14140 return QualType();
14141 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14142 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14143 // An operand with volatile-qualified type is deprecated
14144 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14145 << IsInc << ResType;
14147 // In C++, a prefix increment is the same type as the operand. Otherwise
14148 // (in C or with postfix), the increment is the unqualified type of the
14149 // operand.
14150 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14151 VK = VK_LValue;
14152 OK = Op->getObjectKind();
14153 return ResType;
14154 } else {
14155 VK = VK_PRValue;
14156 return ResType.getUnqualifiedType();
14161 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14162 /// This routine allows us to typecheck complex/recursive expressions
14163 /// where the declaration is needed for type checking. We only need to
14164 /// handle cases when the expression references a function designator
14165 /// or is an lvalue. Here are some examples:
14166 /// - &(x) => x
14167 /// - &*****f => f for f a function designator.
14168 /// - &s.xx => s
14169 /// - &s.zz[1].yy -> s, if zz is an array
14170 /// - *(x + 1) -> x, if x is an array
14171 /// - &"123"[2] -> 0
14172 /// - & __real__ x -> x
14174 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14175 /// members.
14176 static ValueDecl *getPrimaryDecl(Expr *E) {
14177 switch (E->getStmtClass()) {
14178 case Stmt::DeclRefExprClass:
14179 return cast<DeclRefExpr>(E)->getDecl();
14180 case Stmt::MemberExprClass:
14181 // If this is an arrow operator, the address is an offset from
14182 // the base's value, so the object the base refers to is
14183 // irrelevant.
14184 if (cast<MemberExpr>(E)->isArrow())
14185 return nullptr;
14186 // Otherwise, the expression refers to a part of the base
14187 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14188 case Stmt::ArraySubscriptExprClass: {
14189 // FIXME: This code shouldn't be necessary! We should catch the implicit
14190 // promotion of register arrays earlier.
14191 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14192 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14193 if (ICE->getSubExpr()->getType()->isArrayType())
14194 return getPrimaryDecl(ICE->getSubExpr());
14196 return nullptr;
14198 case Stmt::UnaryOperatorClass: {
14199 UnaryOperator *UO = cast<UnaryOperator>(E);
14201 switch(UO->getOpcode()) {
14202 case UO_Real:
14203 case UO_Imag:
14204 case UO_Extension:
14205 return getPrimaryDecl(UO->getSubExpr());
14206 default:
14207 return nullptr;
14210 case Stmt::ParenExprClass:
14211 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14212 case Stmt::ImplicitCastExprClass:
14213 // If the result of an implicit cast is an l-value, we care about
14214 // the sub-expression; otherwise, the result here doesn't matter.
14215 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14216 case Stmt::CXXUuidofExprClass:
14217 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14218 default:
14219 return nullptr;
14223 namespace {
14224 enum {
14225 AO_Bit_Field = 0,
14226 AO_Vector_Element = 1,
14227 AO_Property_Expansion = 2,
14228 AO_Register_Variable = 3,
14229 AO_Matrix_Element = 4,
14230 AO_No_Error = 5
14233 /// Diagnose invalid operand for address of operations.
14235 /// \param Type The type of operand which cannot have its address taken.
14236 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
14237 Expr *E, unsigned Type) {
14238 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14241 /// CheckAddressOfOperand - The operand of & must be either a function
14242 /// designator or an lvalue designating an object. If it is an lvalue, the
14243 /// object cannot be declared with storage class register or be a bit field.
14244 /// Note: The usual conversions are *not* applied to the operand of the &
14245 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
14246 /// In C++, the operand might be an overloaded function name, in which case
14247 /// we allow the '&' but retain the overloaded-function type.
14248 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
14249 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14250 if (PTy->getKind() == BuiltinType::Overload) {
14251 Expr *E = OrigOp.get()->IgnoreParens();
14252 if (!isa<OverloadExpr>(E)) {
14253 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14254 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14255 << OrigOp.get()->getSourceRange();
14256 return QualType();
14259 OverloadExpr *Ovl = cast<OverloadExpr>(E);
14260 if (isa<UnresolvedMemberExpr>(Ovl))
14261 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
14262 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14263 << OrigOp.get()->getSourceRange();
14264 return QualType();
14267 return Context.OverloadTy;
14270 if (PTy->getKind() == BuiltinType::UnknownAny)
14271 return Context.UnknownAnyTy;
14273 if (PTy->getKind() == BuiltinType::BoundMember) {
14274 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14275 << OrigOp.get()->getSourceRange();
14276 return QualType();
14279 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14280 if (OrigOp.isInvalid()) return QualType();
14283 if (OrigOp.get()->isTypeDependent())
14284 return Context.DependentTy;
14286 assert(!OrigOp.get()->hasPlaceholderType());
14288 // Make sure to ignore parentheses in subsequent checks
14289 Expr *op = OrigOp.get()->IgnoreParens();
14291 // In OpenCL captures for blocks called as lambda functions
14292 // are located in the private address space. Blocks used in
14293 // enqueue_kernel can be located in a different address space
14294 // depending on a vendor implementation. Thus preventing
14295 // taking an address of the capture to avoid invalid AS casts.
14296 if (LangOpts.OpenCL) {
14297 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14298 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14299 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14300 return QualType();
14304 if (getLangOpts().C99) {
14305 // Implement C99-only parts of addressof rules.
14306 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14307 if (uOp->getOpcode() == UO_Deref)
14308 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14309 // (assuming the deref expression is valid).
14310 return uOp->getSubExpr()->getType();
14312 // Technically, there should be a check for array subscript
14313 // expressions here, but the result of one is always an lvalue anyway.
14315 ValueDecl *dcl = getPrimaryDecl(op);
14317 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14318 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14319 op->getBeginLoc()))
14320 return QualType();
14322 Expr::LValueClassification lval = op->ClassifyLValue(Context);
14323 unsigned AddressOfError = AO_No_Error;
14325 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14326 bool sfinae = (bool)isSFINAEContext();
14327 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14328 : diag::ext_typecheck_addrof_temporary)
14329 << op->getType() << op->getSourceRange();
14330 if (sfinae)
14331 return QualType();
14332 // Materialize the temporary as an lvalue so that we can take its address.
14333 OrigOp = op =
14334 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14335 } else if (isa<ObjCSelectorExpr>(op)) {
14336 return Context.getPointerType(op->getType());
14337 } else if (lval == Expr::LV_MemberFunction) {
14338 // If it's an instance method, make a member pointer.
14339 // The expression must have exactly the form &A::foo.
14341 // If the underlying expression isn't a decl ref, give up.
14342 if (!isa<DeclRefExpr>(op)) {
14343 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14344 << OrigOp.get()->getSourceRange();
14345 return QualType();
14347 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14348 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14350 // The id-expression was parenthesized.
14351 if (OrigOp.get() != DRE) {
14352 Diag(OpLoc, diag::err_parens_pointer_member_function)
14353 << OrigOp.get()->getSourceRange();
14355 // The method was named without a qualifier.
14356 } else if (!DRE->getQualifier()) {
14357 if (MD->getParent()->getName().empty())
14358 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14359 << op->getSourceRange();
14360 else {
14361 SmallString<32> Str;
14362 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14363 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14364 << op->getSourceRange()
14365 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
14369 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14370 if (isa<CXXDestructorDecl>(MD))
14371 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
14373 QualType MPTy = Context.getMemberPointerType(
14374 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
14375 // Under the MS ABI, lock down the inheritance model now.
14376 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14377 (void)isCompleteType(OpLoc, MPTy);
14378 return MPTy;
14379 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14380 // C99 6.5.3.2p1
14381 // The operand must be either an l-value or a function designator
14382 if (!op->getType()->isFunctionType()) {
14383 // Use a special diagnostic for loads from property references.
14384 if (isa<PseudoObjectExpr>(op)) {
14385 AddressOfError = AO_Property_Expansion;
14386 } else {
14387 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14388 << op->getType() << op->getSourceRange();
14389 return QualType();
14392 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14393 // The operand cannot be a bit-field
14394 AddressOfError = AO_Bit_Field;
14395 } else if (op->getObjectKind() == OK_VectorComponent) {
14396 // The operand cannot be an element of a vector
14397 AddressOfError = AO_Vector_Element;
14398 } else if (op->getObjectKind() == OK_MatrixComponent) {
14399 // The operand cannot be an element of a matrix.
14400 AddressOfError = AO_Matrix_Element;
14401 } else if (dcl) { // C99 6.5.3.2p1
14402 // We have an lvalue with a decl. Make sure the decl is not declared
14403 // with the register storage-class specifier.
14404 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14405 // in C++ it is not error to take address of a register
14406 // variable (c++03 7.1.1P3)
14407 if (vd->getStorageClass() == SC_Register &&
14408 !getLangOpts().CPlusPlus) {
14409 AddressOfError = AO_Register_Variable;
14411 } else if (isa<MSPropertyDecl>(dcl)) {
14412 AddressOfError = AO_Property_Expansion;
14413 } else if (isa<FunctionTemplateDecl>(dcl)) {
14414 return Context.OverloadTy;
14415 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14416 // Okay: we can take the address of a field.
14417 // Could be a pointer to member, though, if there is an explicit
14418 // scope qualifier for the class.
14419 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
14420 DeclContext *Ctx = dcl->getDeclContext();
14421 if (Ctx && Ctx->isRecord()) {
14422 if (dcl->getType()->isReferenceType()) {
14423 Diag(OpLoc,
14424 diag::err_cannot_form_pointer_to_member_of_reference_type)
14425 << dcl->getDeclName() << dcl->getType();
14426 return QualType();
14429 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14430 Ctx = Ctx->getParent();
14432 QualType MPTy = Context.getMemberPointerType(
14433 op->getType(),
14434 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
14435 // Under the MS ABI, lock down the inheritance model now.
14436 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14437 (void)isCompleteType(OpLoc, MPTy);
14438 return MPTy;
14441 } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl,
14442 MSGuidDecl, UnnamedGlobalConstantDecl>(dcl))
14443 llvm_unreachable("Unknown/unexpected decl type");
14446 if (AddressOfError != AO_No_Error) {
14447 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14448 return QualType();
14451 if (lval == Expr::LV_IncompleteVoidType) {
14452 // Taking the address of a void variable is technically illegal, but we
14453 // allow it in cases which are otherwise valid.
14454 // Example: "extern void x; void* y = &x;".
14455 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14458 // If the operand has type "type", the result has type "pointer to type".
14459 if (op->getType()->isObjCObjectType())
14460 return Context.getObjCObjectPointerType(op->getType());
14462 CheckAddressOfPackedMember(op);
14464 return Context.getPointerType(op->getType());
14467 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14468 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14469 if (!DRE)
14470 return;
14471 const Decl *D = DRE->getDecl();
14472 if (!D)
14473 return;
14474 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14475 if (!Param)
14476 return;
14477 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14478 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14479 return;
14480 if (FunctionScopeInfo *FD = S.getCurFunction())
14481 FD->ModifiedNonNullParams.insert(Param);
14484 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14485 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
14486 SourceLocation OpLoc) {
14487 if (Op->isTypeDependent())
14488 return S.Context.DependentTy;
14490 ExprResult ConvResult = S.UsualUnaryConversions(Op);
14491 if (ConvResult.isInvalid())
14492 return QualType();
14493 Op = ConvResult.get();
14494 QualType OpTy = Op->getType();
14495 QualType Result;
14497 if (isa<CXXReinterpretCastExpr>(Op)) {
14498 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14499 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14500 Op->getSourceRange());
14503 if (const PointerType *PT = OpTy->getAs<PointerType>())
14505 Result = PT->getPointeeType();
14507 else if (const ObjCObjectPointerType *OPT =
14508 OpTy->getAs<ObjCObjectPointerType>())
14509 Result = OPT->getPointeeType();
14510 else {
14511 ExprResult PR = S.CheckPlaceholderExpr(Op);
14512 if (PR.isInvalid()) return QualType();
14513 if (PR.get() != Op)
14514 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14517 if (Result.isNull()) {
14518 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14519 << OpTy << Op->getSourceRange();
14520 return QualType();
14523 // Note that per both C89 and C99, indirection is always legal, even if Result
14524 // is an incomplete type or void. It would be possible to warn about
14525 // dereferencing a void pointer, but it's completely well-defined, and such a
14526 // warning is unlikely to catch any mistakes. In C++, indirection is not valid
14527 // for pointers to 'void' but is fine for any other pointer type:
14529 // C++ [expr.unary.op]p1:
14530 // [...] the expression to which [the unary * operator] is applied shall
14531 // be a pointer to an object type, or a pointer to a function type
14532 if (S.getLangOpts().CPlusPlus && Result->isVoidType())
14533 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14534 << OpTy << Op->getSourceRange();
14536 // Dereferences are usually l-values...
14537 VK = VK_LValue;
14539 // ...except that certain expressions are never l-values in C.
14540 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14541 VK = VK_PRValue;
14543 return Result;
14546 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14547 BinaryOperatorKind Opc;
14548 switch (Kind) {
14549 default: llvm_unreachable("Unknown binop!");
14550 case tok::periodstar: Opc = BO_PtrMemD; break;
14551 case tok::arrowstar: Opc = BO_PtrMemI; break;
14552 case tok::star: Opc = BO_Mul; break;
14553 case tok::slash: Opc = BO_Div; break;
14554 case tok::percent: Opc = BO_Rem; break;
14555 case tok::plus: Opc = BO_Add; break;
14556 case tok::minus: Opc = BO_Sub; break;
14557 case tok::lessless: Opc = BO_Shl; break;
14558 case tok::greatergreater: Opc = BO_Shr; break;
14559 case tok::lessequal: Opc = BO_LE; break;
14560 case tok::less: Opc = BO_LT; break;
14561 case tok::greaterequal: Opc = BO_GE; break;
14562 case tok::greater: Opc = BO_GT; break;
14563 case tok::exclaimequal: Opc = BO_NE; break;
14564 case tok::equalequal: Opc = BO_EQ; break;
14565 case tok::spaceship: Opc = BO_Cmp; break;
14566 case tok::amp: Opc = BO_And; break;
14567 case tok::caret: Opc = BO_Xor; break;
14568 case tok::pipe: Opc = BO_Or; break;
14569 case tok::ampamp: Opc = BO_LAnd; break;
14570 case tok::pipepipe: Opc = BO_LOr; break;
14571 case tok::equal: Opc = BO_Assign; break;
14572 case tok::starequal: Opc = BO_MulAssign; break;
14573 case tok::slashequal: Opc = BO_DivAssign; break;
14574 case tok::percentequal: Opc = BO_RemAssign; break;
14575 case tok::plusequal: Opc = BO_AddAssign; break;
14576 case tok::minusequal: Opc = BO_SubAssign; break;
14577 case tok::lesslessequal: Opc = BO_ShlAssign; break;
14578 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
14579 case tok::ampequal: Opc = BO_AndAssign; break;
14580 case tok::caretequal: Opc = BO_XorAssign; break;
14581 case tok::pipeequal: Opc = BO_OrAssign; break;
14582 case tok::comma: Opc = BO_Comma; break;
14584 return Opc;
14587 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
14588 tok::TokenKind Kind) {
14589 UnaryOperatorKind Opc;
14590 switch (Kind) {
14591 default: llvm_unreachable("Unknown unary op!");
14592 case tok::plusplus: Opc = UO_PreInc; break;
14593 case tok::minusminus: Opc = UO_PreDec; break;
14594 case tok::amp: Opc = UO_AddrOf; break;
14595 case tok::star: Opc = UO_Deref; break;
14596 case tok::plus: Opc = UO_Plus; break;
14597 case tok::minus: Opc = UO_Minus; break;
14598 case tok::tilde: Opc = UO_Not; break;
14599 case tok::exclaim: Opc = UO_LNot; break;
14600 case tok::kw___real: Opc = UO_Real; break;
14601 case tok::kw___imag: Opc = UO_Imag; break;
14602 case tok::kw___extension__: Opc = UO_Extension; break;
14604 return Opc;
14607 const FieldDecl *
14608 Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {
14609 // Explore the case for adding 'this->' to the LHS of a self assignment, very
14610 // common for setters.
14611 // struct A {
14612 // int X;
14613 // -void setX(int X) { X = X; }
14614 // +void setX(int X) { this->X = X; }
14615 // };
14617 // Only consider parameters for self assignment fixes.
14618 if (!isa<ParmVarDecl>(SelfAssigned))
14619 return nullptr;
14620 const auto *Method =
14621 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
14622 if (!Method)
14623 return nullptr;
14625 const CXXRecordDecl *Parent = Method->getParent();
14626 // In theory this is fixable if the lambda explicitly captures this, but
14627 // that's added complexity that's rarely going to be used.
14628 if (Parent->isLambda())
14629 return nullptr;
14631 // FIXME: Use an actual Lookup operation instead of just traversing fields
14632 // in order to get base class fields.
14633 auto Field =
14634 llvm::find_if(Parent->fields(),
14635 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
14636 return F->getDeclName() == Name;
14638 return (Field != Parent->field_end()) ? *Field : nullptr;
14641 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14642 /// This warning suppressed in the event of macro expansions.
14643 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14644 SourceLocation OpLoc, bool IsBuiltin) {
14645 if (S.inTemplateInstantiation())
14646 return;
14647 if (S.isUnevaluatedContext())
14648 return;
14649 if (OpLoc.isInvalid() || OpLoc.isMacroID())
14650 return;
14651 LHSExpr = LHSExpr->IgnoreParenImpCasts();
14652 RHSExpr = RHSExpr->IgnoreParenImpCasts();
14653 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14654 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14655 if (!LHSDeclRef || !RHSDeclRef ||
14656 LHSDeclRef->getLocation().isMacroID() ||
14657 RHSDeclRef->getLocation().isMacroID())
14658 return;
14659 const ValueDecl *LHSDecl =
14660 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14661 const ValueDecl *RHSDecl =
14662 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14663 if (LHSDecl != RHSDecl)
14664 return;
14665 if (LHSDecl->getType().isVolatileQualified())
14666 return;
14667 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14668 if (RefTy->getPointeeType().isVolatileQualified())
14669 return;
14671 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14672 : diag::warn_self_assignment_overloaded)
14673 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14674 << RHSExpr->getSourceRange();
14675 if (const FieldDecl *SelfAssignField =
14676 S.getSelfAssignmentClassMemberCandidate(RHSDecl))
14677 Diag << 1 << SelfAssignField
14678 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
14679 else
14680 Diag << 0;
14683 /// Check if a bitwise-& is performed on an Objective-C pointer. This
14684 /// is usually indicative of introspection within the Objective-C pointer.
14685 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
14686 SourceLocation OpLoc) {
14687 if (!S.getLangOpts().ObjC)
14688 return;
14690 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14691 const Expr *LHS = L.get();
14692 const Expr *RHS = R.get();
14694 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14695 ObjCPointerExpr = LHS;
14696 OtherExpr = RHS;
14698 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14699 ObjCPointerExpr = RHS;
14700 OtherExpr = LHS;
14703 // This warning is deliberately made very specific to reduce false
14704 // positives with logic that uses '&' for hashing. This logic mainly
14705 // looks for code trying to introspect into tagged pointers, which
14706 // code should generally never do.
14707 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14708 unsigned Diag = diag::warn_objc_pointer_masking;
14709 // Determine if we are introspecting the result of performSelectorXXX.
14710 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14711 // Special case messages to -performSelector and friends, which
14712 // can return non-pointer values boxed in a pointer value.
14713 // Some clients may wish to silence warnings in this subcase.
14714 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14715 Selector S = ME->getSelector();
14716 StringRef SelArg0 = S.getNameForSlot(0);
14717 if (SelArg0.startswith("performSelector"))
14718 Diag = diag::warn_objc_pointer_masking_performSelector;
14721 S.Diag(OpLoc, Diag)
14722 << ObjCPointerExpr->getSourceRange();
14726 static NamedDecl *getDeclFromExpr(Expr *E) {
14727 if (!E)
14728 return nullptr;
14729 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14730 return DRE->getDecl();
14731 if (auto *ME = dyn_cast<MemberExpr>(E))
14732 return ME->getMemberDecl();
14733 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14734 return IRE->getDecl();
14735 return nullptr;
14738 // This helper function promotes a binary operator's operands (which are of a
14739 // half vector type) to a vector of floats and then truncates the result to
14740 // a vector of either half or short.
14741 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
14742 BinaryOperatorKind Opc, QualType ResultTy,
14743 ExprValueKind VK, ExprObjectKind OK,
14744 bool IsCompAssign, SourceLocation OpLoc,
14745 FPOptionsOverride FPFeatures) {
14746 auto &Context = S.getASTContext();
14747 assert((isVector(ResultTy, Context.HalfTy) ||
14748 isVector(ResultTy, Context.ShortTy)) &&
14749 "Result must be a vector of half or short");
14750 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
14751 isVector(RHS.get()->getType(), Context.HalfTy) &&
14752 "both operands expected to be a half vector");
14754 RHS = convertVector(RHS.get(), Context.FloatTy, S);
14755 QualType BinOpResTy = RHS.get()->getType();
14757 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14758 // change BinOpResTy to a vector of ints.
14759 if (isVector(ResultTy, Context.ShortTy))
14760 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14762 if (IsCompAssign)
14763 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14764 ResultTy, VK, OK, OpLoc, FPFeatures,
14765 BinOpResTy, BinOpResTy);
14767 LHS = convertVector(LHS.get(), Context.FloatTy, S);
14768 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14769 BinOpResTy, VK, OK, OpLoc, FPFeatures);
14770 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14773 static std::pair<ExprResult, ExprResult>
14774 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
14775 Expr *RHSExpr) {
14776 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14777 if (!S.Context.isDependenceAllowed()) {
14778 // C cannot handle TypoExpr nodes on either side of a binop because it
14779 // doesn't handle dependent types properly, so make sure any TypoExprs have
14780 // been dealt with before checking the operands.
14781 LHS = S.CorrectDelayedTyposInExpr(LHS);
14782 RHS = S.CorrectDelayedTyposInExpr(
14783 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14784 [Opc, LHS](Expr *E) {
14785 if (Opc != BO_Assign)
14786 return ExprResult(E);
14787 // Avoid correcting the RHS to the same Expr as the LHS.
14788 Decl *D = getDeclFromExpr(E);
14789 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14792 return std::make_pair(LHS, RHS);
14795 /// Returns true if conversion between vectors of halfs and vectors of floats
14796 /// is needed.
14797 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14798 Expr *E0, Expr *E1 = nullptr) {
14799 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14800 Ctx.getTargetInfo().useFP16ConversionIntrinsics())
14801 return false;
14803 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14804 QualType Ty = E->IgnoreImplicit()->getType();
14806 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14807 // to vectors of floats. Although the element type of the vectors is __fp16,
14808 // the vectors shouldn't be treated as storage-only types. See the
14809 // discussion here: https://reviews.llvm.org/rG825235c140e7
14810 if (const VectorType *VT = Ty->getAs<VectorType>()) {
14811 if (VT->getVectorKind() == VectorType::NeonVector)
14812 return false;
14813 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14815 return false;
14818 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14821 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
14822 /// operator @p Opc at location @c TokLoc. This routine only supports
14823 /// built-in operations; ActOnBinOp handles overloaded operators.
14824 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
14825 BinaryOperatorKind Opc,
14826 Expr *LHSExpr, Expr *RHSExpr) {
14827 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14828 // The syntax only allows initializer lists on the RHS of assignment,
14829 // so we don't need to worry about accepting invalid code for
14830 // non-assignment operators.
14831 // C++11 5.17p9:
14832 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14833 // of x = {} is x = T().
14834 InitializationKind Kind = InitializationKind::CreateDirectList(
14835 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14836 InitializedEntity Entity =
14837 InitializedEntity::InitializeTemporary(LHSExpr->getType());
14838 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14839 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14840 if (Init.isInvalid())
14841 return Init;
14842 RHSExpr = Init.get();
14845 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14846 QualType ResultTy; // Result type of the binary operator.
14847 // The following two variables are used for compound assignment operators
14848 QualType CompLHSTy; // Type of LHS after promotions for computation
14849 QualType CompResultTy; // Type of computation result
14850 ExprValueKind VK = VK_PRValue;
14851 ExprObjectKind OK = OK_Ordinary;
14852 bool ConvertHalfVec = false;
14854 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14855 if (!LHS.isUsable() || !RHS.isUsable())
14856 return ExprError();
14858 if (getLangOpts().OpenCL) {
14859 QualType LHSTy = LHSExpr->getType();
14860 QualType RHSTy = RHSExpr->getType();
14861 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14862 // the ATOMIC_VAR_INIT macro.
14863 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14864 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14865 if (BO_Assign == Opc)
14866 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14867 else
14868 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14869 return ExprError();
14872 // OpenCL special types - image, sampler, pipe, and blocks are to be used
14873 // only with a builtin functions and therefore should be disallowed here.
14874 if (LHSTy->isImageType() || RHSTy->isImageType() ||
14875 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14876 LHSTy->isPipeType() || RHSTy->isPipeType() ||
14877 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14878 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14879 return ExprError();
14883 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14884 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14886 switch (Opc) {
14887 case BO_Assign:
14888 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
14889 if (getLangOpts().CPlusPlus &&
14890 LHS.get()->getObjectKind() != OK_ObjCProperty) {
14891 VK = LHS.get()->getValueKind();
14892 OK = LHS.get()->getObjectKind();
14894 if (!ResultTy.isNull()) {
14895 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14896 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14898 // Avoid copying a block to the heap if the block is assigned to a local
14899 // auto variable that is declared in the same scope as the block. This
14900 // optimization is unsafe if the local variable is declared in an outer
14901 // scope. For example:
14903 // BlockTy b;
14904 // {
14905 // b = ^{...};
14906 // }
14907 // // It is unsafe to invoke the block here if it wasn't copied to the
14908 // // heap.
14909 // b();
14911 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14912 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14913 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14914 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14915 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14917 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
14918 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14919 NTCUC_Assignment, NTCUK_Copy);
14921 RecordModifiableNonNullParam(*this, LHS.get());
14922 break;
14923 case BO_PtrMemD:
14924 case BO_PtrMemI:
14925 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14926 Opc == BO_PtrMemI);
14927 break;
14928 case BO_Mul:
14929 case BO_Div:
14930 ConvertHalfVec = true;
14931 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14932 Opc == BO_Div);
14933 break;
14934 case BO_Rem:
14935 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14936 break;
14937 case BO_Add:
14938 ConvertHalfVec = true;
14939 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14940 break;
14941 case BO_Sub:
14942 ConvertHalfVec = true;
14943 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14944 break;
14945 case BO_Shl:
14946 case BO_Shr:
14947 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14948 break;
14949 case BO_LE:
14950 case BO_LT:
14951 case BO_GE:
14952 case BO_GT:
14953 ConvertHalfVec = true;
14954 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14955 break;
14956 case BO_EQ:
14957 case BO_NE:
14958 ConvertHalfVec = true;
14959 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14960 break;
14961 case BO_Cmp:
14962 ConvertHalfVec = true;
14963 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14964 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
14965 break;
14966 case BO_And:
14967 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14968 [[fallthrough]];
14969 case BO_Xor:
14970 case BO_Or:
14971 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14972 break;
14973 case BO_LAnd:
14974 case BO_LOr:
14975 ConvertHalfVec = true;
14976 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14977 break;
14978 case BO_MulAssign:
14979 case BO_DivAssign:
14980 ConvertHalfVec = true;
14981 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14982 Opc == BO_DivAssign);
14983 CompLHSTy = CompResultTy;
14984 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14985 ResultTy =
14986 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14987 break;
14988 case BO_RemAssign:
14989 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14990 CompLHSTy = CompResultTy;
14991 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14992 ResultTy =
14993 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14994 break;
14995 case BO_AddAssign:
14996 ConvertHalfVec = true;
14997 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14998 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14999 ResultTy =
15000 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15001 break;
15002 case BO_SubAssign:
15003 ConvertHalfVec = true;
15004 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
15005 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15006 ResultTy =
15007 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15008 break;
15009 case BO_ShlAssign:
15010 case BO_ShrAssign:
15011 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15012 CompLHSTy = CompResultTy;
15013 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15014 ResultTy =
15015 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15016 break;
15017 case BO_AndAssign:
15018 case BO_OrAssign: // fallthrough
15019 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15020 [[fallthrough]];
15021 case BO_XorAssign:
15022 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15023 CompLHSTy = CompResultTy;
15024 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15025 ResultTy =
15026 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15027 break;
15028 case BO_Comma:
15029 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15030 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15031 VK = RHS.get()->getValueKind();
15032 OK = RHS.get()->getObjectKind();
15034 break;
15036 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15037 return ExprError();
15039 // Some of the binary operations require promoting operands of half vector to
15040 // float vectors and truncating the result back to half vector. For now, we do
15041 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15042 // arm64).
15043 assert(
15044 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15045 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15046 "both sides are half vectors or neither sides are");
15047 ConvertHalfVec =
15048 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15050 // Check for array bounds violations for both sides of the BinaryOperator
15051 CheckArrayAccess(LHS.get());
15052 CheckArrayAccess(RHS.get());
15054 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15055 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15056 &Context.Idents.get("object_setClass"),
15057 SourceLocation(), LookupOrdinaryName);
15058 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15059 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15060 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15061 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
15062 "object_setClass(")
15063 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15064 ",")
15065 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15067 else
15068 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15070 else if (const ObjCIvarRefExpr *OIRE =
15071 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15072 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15074 // Opc is not a compound assignment if CompResultTy is null.
15075 if (CompResultTy.isNull()) {
15076 if (ConvertHalfVec)
15077 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15078 OpLoc, CurFPFeatureOverrides());
15079 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15080 VK, OK, OpLoc, CurFPFeatureOverrides());
15083 // Handle compound assignments.
15084 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15085 OK_ObjCProperty) {
15086 VK = VK_LValue;
15087 OK = LHS.get()->getObjectKind();
15090 // The LHS is not converted to the result type for fixed-point compound
15091 // assignment as the common type is computed on demand. Reset the CompLHSTy
15092 // to the LHS type we would have gotten after unary conversions.
15093 if (CompResultTy->isFixedPointType())
15094 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15096 if (ConvertHalfVec)
15097 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15098 OpLoc, CurFPFeatureOverrides());
15100 return CompoundAssignOperator::Create(
15101 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15102 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15105 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15106 /// operators are mixed in a way that suggests that the programmer forgot that
15107 /// comparison operators have higher precedence. The most typical example of
15108 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15109 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
15110 SourceLocation OpLoc, Expr *LHSExpr,
15111 Expr *RHSExpr) {
15112 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15113 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15115 // Check that one of the sides is a comparison operator and the other isn't.
15116 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15117 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15118 if (isLeftComp == isRightComp)
15119 return;
15121 // Bitwise operations are sometimes used as eager logical ops.
15122 // Don't diagnose this.
15123 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15124 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15125 if (isLeftBitwise || isRightBitwise)
15126 return;
15128 SourceRange DiagRange = isLeftComp
15129 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15130 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15131 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15132 SourceRange ParensRange =
15133 isLeftComp
15134 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15135 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15137 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15138 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15139 SuggestParentheses(Self, OpLoc,
15140 Self.PDiag(diag::note_precedence_silence) << OpStr,
15141 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15142 SuggestParentheses(Self, OpLoc,
15143 Self.PDiag(diag::note_precedence_bitwise_first)
15144 << BinaryOperator::getOpcodeStr(Opc),
15145 ParensRange);
15148 /// It accepts a '&&' expr that is inside a '||' one.
15149 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15150 /// in parentheses.
15151 static void
15152 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
15153 BinaryOperator *Bop) {
15154 assert(Bop->getOpcode() == BO_LAnd);
15155 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15156 << Bop->getSourceRange() << OpLoc;
15157 SuggestParentheses(Self, Bop->getOperatorLoc(),
15158 Self.PDiag(diag::note_precedence_silence)
15159 << Bop->getOpcodeStr(),
15160 Bop->getSourceRange());
15163 /// Returns true if the given expression can be evaluated as a constant
15164 /// 'true'.
15165 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
15166 bool Res;
15167 return !E->isValueDependent() &&
15168 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
15171 /// Returns true if the given expression can be evaluated as a constant
15172 /// 'false'.
15173 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
15174 bool Res;
15175 return !E->isValueDependent() &&
15176 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
15179 /// Look for '&&' in the left hand of a '||' expr.
15180 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
15181 Expr *LHSExpr, Expr *RHSExpr) {
15182 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15183 if (Bop->getOpcode() == BO_LAnd) {
15184 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
15185 if (EvaluatesAsFalse(S, RHSExpr))
15186 return;
15187 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
15188 if (!EvaluatesAsTrue(S, Bop->getLHS()))
15189 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15190 } else if (Bop->getOpcode() == BO_LOr) {
15191 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15192 // If it's "a || b && 1 || c" we didn't warn earlier for
15193 // "a || b && 1", but warn now.
15194 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
15195 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15201 /// Look for '&&' in the right hand of a '||' expr.
15202 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
15203 Expr *LHSExpr, Expr *RHSExpr) {
15204 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15205 if (Bop->getOpcode() == BO_LAnd) {
15206 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
15207 if (EvaluatesAsFalse(S, LHSExpr))
15208 return;
15209 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
15210 if (!EvaluatesAsTrue(S, Bop->getRHS()))
15211 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15216 /// Look for bitwise op in the left or right hand of a bitwise op with
15217 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
15218 /// the '&' expression in parentheses.
15219 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
15220 SourceLocation OpLoc, Expr *SubExpr) {
15221 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15222 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15223 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15224 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15225 << Bop->getSourceRange() << OpLoc;
15226 SuggestParentheses(S, Bop->getOperatorLoc(),
15227 S.PDiag(diag::note_precedence_silence)
15228 << Bop->getOpcodeStr(),
15229 Bop->getSourceRange());
15234 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
15235 Expr *SubExpr, StringRef Shift) {
15236 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15237 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15238 StringRef Op = Bop->getOpcodeStr();
15239 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15240 << Bop->getSourceRange() << OpLoc << Shift << Op;
15241 SuggestParentheses(S, Bop->getOperatorLoc(),
15242 S.PDiag(diag::note_precedence_silence) << Op,
15243 Bop->getSourceRange());
15248 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
15249 Expr *LHSExpr, Expr *RHSExpr) {
15250 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15251 if (!OCE)
15252 return;
15254 FunctionDecl *FD = OCE->getDirectCallee();
15255 if (!FD || !FD->isOverloadedOperator())
15256 return;
15258 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
15259 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15260 return;
15262 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15263 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15264 << (Kind == OO_LessLess);
15265 SuggestParentheses(S, OCE->getOperatorLoc(),
15266 S.PDiag(diag::note_precedence_silence)
15267 << (Kind == OO_LessLess ? "<<" : ">>"),
15268 OCE->getSourceRange());
15269 SuggestParentheses(
15270 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15271 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15274 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15275 /// precedence.
15276 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
15277 SourceLocation OpLoc, Expr *LHSExpr,
15278 Expr *RHSExpr){
15279 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15280 if (BinaryOperator::isBitwiseOp(Opc))
15281 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15283 // Diagnose "arg1 & arg2 | arg3"
15284 if ((Opc == BO_Or || Opc == BO_Xor) &&
15285 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15286 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15287 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15290 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15291 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15292 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15293 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15294 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15297 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15298 || Opc == BO_Shr) {
15299 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15300 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15301 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15304 // Warn on overloaded shift operators and comparisons, such as:
15305 // cout << 5 == 4;
15306 if (BinaryOperator::isComparisonOp(Opc))
15307 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15310 // Binary Operators. 'Tok' is the token for the operator.
15311 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
15312 tok::TokenKind Kind,
15313 Expr *LHSExpr, Expr *RHSExpr) {
15314 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15315 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15316 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15318 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15319 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15321 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15324 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
15325 UnresolvedSetImpl &Functions) {
15326 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
15327 if (OverOp != OO_None && OverOp != OO_Equal)
15328 LookupOverloadedOperatorName(OverOp, S, Functions);
15330 // In C++20 onwards, we may have a second operator to look up.
15331 if (getLangOpts().CPlusPlus20) {
15332 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
15333 LookupOverloadedOperatorName(ExtraOp, S, Functions);
15337 /// Build an overloaded binary operator expression in the given scope.
15338 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
15339 BinaryOperatorKind Opc,
15340 Expr *LHS, Expr *RHS) {
15341 switch (Opc) {
15342 case BO_Assign:
15343 case BO_DivAssign:
15344 case BO_RemAssign:
15345 case BO_SubAssign:
15346 case BO_AndAssign:
15347 case BO_OrAssign:
15348 case BO_XorAssign:
15349 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15350 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15351 break;
15352 default:
15353 break;
15356 // Find all of the overloaded operators visible from this point.
15357 UnresolvedSet<16> Functions;
15358 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15360 // Build the (potentially-overloaded, potentially-dependent)
15361 // binary operation.
15362 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15365 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
15366 BinaryOperatorKind Opc,
15367 Expr *LHSExpr, Expr *RHSExpr) {
15368 ExprResult LHS, RHS;
15369 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15370 if (!LHS.isUsable() || !RHS.isUsable())
15371 return ExprError();
15372 LHSExpr = LHS.get();
15373 RHSExpr = RHS.get();
15375 // We want to end up calling one of checkPseudoObjectAssignment
15376 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15377 // both expressions are overloadable or either is type-dependent),
15378 // or CreateBuiltinBinOp (in any other case). We also want to get
15379 // any placeholder types out of the way.
15381 // Handle pseudo-objects in the LHS.
15382 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15383 // Assignments with a pseudo-object l-value need special analysis.
15384 if (pty->getKind() == BuiltinType::PseudoObject &&
15385 BinaryOperator::isAssignmentOp(Opc))
15386 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15388 // Don't resolve overloads if the other type is overloadable.
15389 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15390 // We can't actually test that if we still have a placeholder,
15391 // though. Fortunately, none of the exceptions we see in that
15392 // code below are valid when the LHS is an overload set. Note
15393 // that an overload set can be dependently-typed, but it never
15394 // instantiates to having an overloadable type.
15395 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15396 if (resolvedRHS.isInvalid()) return ExprError();
15397 RHSExpr = resolvedRHS.get();
15399 if (RHSExpr->isTypeDependent() ||
15400 RHSExpr->getType()->isOverloadableType())
15401 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15404 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15405 // template, diagnose the missing 'template' keyword instead of diagnosing
15406 // an invalid use of a bound member function.
15408 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15409 // to C++1z [over.over]/1.4, but we already checked for that case above.
15410 if (Opc == BO_LT && inTemplateInstantiation() &&
15411 (pty->getKind() == BuiltinType::BoundMember ||
15412 pty->getKind() == BuiltinType::Overload)) {
15413 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15414 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15415 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
15416 return isa<FunctionTemplateDecl>(ND);
15417 })) {
15418 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15419 : OE->getNameLoc(),
15420 diag::err_template_kw_missing)
15421 << OE->getName().getAsString() << "";
15422 return ExprError();
15426 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15427 if (LHS.isInvalid()) return ExprError();
15428 LHSExpr = LHS.get();
15431 // Handle pseudo-objects in the RHS.
15432 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15433 // An overload in the RHS can potentially be resolved by the type
15434 // being assigned to.
15435 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15436 if (getLangOpts().CPlusPlus &&
15437 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15438 LHSExpr->getType()->isOverloadableType()))
15439 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15441 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15444 // Don't resolve overloads if the other type is overloadable.
15445 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15446 LHSExpr->getType()->isOverloadableType())
15447 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15449 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15450 if (!resolvedRHS.isUsable()) return ExprError();
15451 RHSExpr = resolvedRHS.get();
15454 if (getLangOpts().CPlusPlus) {
15455 // If either expression is type-dependent, always build an
15456 // overloaded op.
15457 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
15458 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15460 // Otherwise, build an overloaded op if either expression has an
15461 // overloadable type.
15462 if (LHSExpr->getType()->isOverloadableType() ||
15463 RHSExpr->getType()->isOverloadableType())
15464 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15467 if (getLangOpts().RecoveryAST &&
15468 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15469 assert(!getLangOpts().CPlusPlus);
15470 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
15471 "Should only occur in error-recovery path.");
15472 if (BinaryOperator::isCompoundAssignmentOp(Opc))
15473 // C [6.15.16] p3:
15474 // An assignment expression has the value of the left operand after the
15475 // assignment, but is not an lvalue.
15476 return CompoundAssignOperator::Create(
15477 Context, LHSExpr, RHSExpr, Opc,
15478 LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
15479 OpLoc, CurFPFeatureOverrides());
15480 QualType ResultType;
15481 switch (Opc) {
15482 case BO_Assign:
15483 ResultType = LHSExpr->getType().getUnqualifiedType();
15484 break;
15485 case BO_LT:
15486 case BO_GT:
15487 case BO_LE:
15488 case BO_GE:
15489 case BO_EQ:
15490 case BO_NE:
15491 case BO_LAnd:
15492 case BO_LOr:
15493 // These operators have a fixed result type regardless of operands.
15494 ResultType = Context.IntTy;
15495 break;
15496 case BO_Comma:
15497 ResultType = RHSExpr->getType();
15498 break;
15499 default:
15500 ResultType = Context.DependentTy;
15501 break;
15503 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15504 VK_PRValue, OK_Ordinary, OpLoc,
15505 CurFPFeatureOverrides());
15508 // Build a built-in binary operation.
15509 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15512 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
15513 if (T.isNull() || T->isDependentType())
15514 return false;
15516 if (!T->isPromotableIntegerType())
15517 return true;
15519 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15522 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
15523 UnaryOperatorKind Opc,
15524 Expr *InputExpr) {
15525 ExprResult Input = InputExpr;
15526 ExprValueKind VK = VK_PRValue;
15527 ExprObjectKind OK = OK_Ordinary;
15528 QualType resultType;
15529 bool CanOverflow = false;
15531 bool ConvertHalfVec = false;
15532 if (getLangOpts().OpenCL) {
15533 QualType Ty = InputExpr->getType();
15534 // The only legal unary operation for atomics is '&'.
15535 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15536 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15537 // only with a builtin functions and therefore should be disallowed here.
15538 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15539 || Ty->isBlockPointerType())) {
15540 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15541 << InputExpr->getType()
15542 << Input.get()->getSourceRange());
15546 if (getLangOpts().HLSL) {
15547 if (Opc == UO_AddrOf)
15548 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15549 if (Opc == UO_Deref)
15550 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15553 switch (Opc) {
15554 case UO_PreInc:
15555 case UO_PreDec:
15556 case UO_PostInc:
15557 case UO_PostDec:
15558 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
15559 OpLoc,
15560 Opc == UO_PreInc ||
15561 Opc == UO_PostInc,
15562 Opc == UO_PreInc ||
15563 Opc == UO_PreDec);
15564 CanOverflow = isOverflowingIntegerType(Context, resultType);
15565 break;
15566 case UO_AddrOf:
15567 resultType = CheckAddressOfOperand(Input, OpLoc);
15568 CheckAddressOfNoDeref(InputExpr);
15569 RecordModifiableNonNullParam(*this, InputExpr);
15570 break;
15571 case UO_Deref: {
15572 Input = DefaultFunctionArrayLvalueConversion(Input.get());
15573 if (Input.isInvalid()) return ExprError();
15574 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
15575 break;
15577 case UO_Plus:
15578 case UO_Minus:
15579 CanOverflow = Opc == UO_Minus &&
15580 isOverflowingIntegerType(Context, Input.get()->getType());
15581 Input = UsualUnaryConversions(Input.get());
15582 if (Input.isInvalid()) return ExprError();
15583 // Unary plus and minus require promoting an operand of half vector to a
15584 // float vector and truncating the result back to a half vector. For now, we
15585 // do this only when HalfArgsAndReturns is set (that is, when the target is
15586 // arm or arm64).
15587 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15589 // If the operand is a half vector, promote it to a float vector.
15590 if (ConvertHalfVec)
15591 Input = convertVector(Input.get(), Context.FloatTy, *this);
15592 resultType = Input.get()->getType();
15593 if (resultType->isDependentType())
15594 break;
15595 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15596 break;
15597 else if (resultType->isVectorType() &&
15598 // The z vector extensions don't allow + or - with bool vectors.
15599 (!Context.getLangOpts().ZVector ||
15600 resultType->castAs<VectorType>()->getVectorKind() !=
15601 VectorType::AltiVecBool))
15602 break;
15603 else if (resultType->isVLSTBuiltinType()) // SVE vectors allow + and -
15604 break;
15605 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15606 Opc == UO_Plus &&
15607 resultType->isPointerType())
15608 break;
15610 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15611 << resultType << Input.get()->getSourceRange());
15613 case UO_Not: // bitwise complement
15614 Input = UsualUnaryConversions(Input.get());
15615 if (Input.isInvalid())
15616 return ExprError();
15617 resultType = Input.get()->getType();
15618 if (resultType->isDependentType())
15619 break;
15620 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15621 if (resultType->isComplexType() || resultType->isComplexIntegerType())
15622 // C99 does not support '~' for complex conjugation.
15623 Diag(OpLoc, diag::ext_integer_complement_complex)
15624 << resultType << Input.get()->getSourceRange();
15625 else if (resultType->hasIntegerRepresentation())
15626 break;
15627 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15628 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15629 // on vector float types.
15630 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15631 if (!T->isIntegerType())
15632 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15633 << resultType << Input.get()->getSourceRange());
15634 } else {
15635 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15636 << resultType << Input.get()->getSourceRange());
15638 break;
15640 case UO_LNot: // logical negation
15641 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15642 Input = DefaultFunctionArrayLvalueConversion(Input.get());
15643 if (Input.isInvalid()) return ExprError();
15644 resultType = Input.get()->getType();
15646 // Though we still have to promote half FP to float...
15647 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15648 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
15649 resultType = Context.FloatTy;
15652 if (resultType->isDependentType())
15653 break;
15654 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15655 // C99 6.5.3.3p1: ok, fallthrough;
15656 if (Context.getLangOpts().CPlusPlus) {
15657 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15658 // operand contextually converted to bool.
15659 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15660 ScalarTypeToBooleanCastKind(resultType));
15661 } else if (Context.getLangOpts().OpenCL &&
15662 Context.getLangOpts().OpenCLVersion < 120) {
15663 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15664 // operate on scalar float types.
15665 if (!resultType->isIntegerType() && !resultType->isPointerType())
15666 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15667 << resultType << Input.get()->getSourceRange());
15669 } else if (resultType->isExtVectorType()) {
15670 if (Context.getLangOpts().OpenCL &&
15671 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
15672 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15673 // operate on vector float types.
15674 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15675 if (!T->isIntegerType())
15676 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15677 << resultType << Input.get()->getSourceRange());
15679 // Vector logical not returns the signed variant of the operand type.
15680 resultType = GetSignedVectorType(resultType);
15681 break;
15682 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
15683 const VectorType *VTy = resultType->castAs<VectorType>();
15684 if (VTy->getVectorKind() != VectorType::GenericVector)
15685 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15686 << resultType << Input.get()->getSourceRange());
15688 // Vector logical not returns the signed variant of the operand type.
15689 resultType = GetSignedVectorType(resultType);
15690 break;
15691 } else {
15692 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15693 << resultType << Input.get()->getSourceRange());
15696 // LNot always has type int. C99 6.5.3.3p5.
15697 // In C++, it's bool. C++ 5.3.1p8
15698 resultType = Context.getLogicalOperationType();
15699 break;
15700 case UO_Real:
15701 case UO_Imag:
15702 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15703 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
15704 // complex l-values to ordinary l-values and all other values to r-values.
15705 if (Input.isInvalid()) return ExprError();
15706 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15707 if (Input.get()->isGLValue() &&
15708 Input.get()->getObjectKind() == OK_Ordinary)
15709 VK = Input.get()->getValueKind();
15710 } else if (!getLangOpts().CPlusPlus) {
15711 // In C, a volatile scalar is read by __imag. In C++, it is not.
15712 Input = DefaultLvalueConversion(Input.get());
15714 break;
15715 case UO_Extension:
15716 resultType = Input.get()->getType();
15717 VK = Input.get()->getValueKind();
15718 OK = Input.get()->getObjectKind();
15719 break;
15720 case UO_Coawait:
15721 // It's unnecessary to represent the pass-through operator co_await in the
15722 // AST; just return the input expression instead.
15723 assert(!Input.get()->getType()->isDependentType() &&
15724 "the co_await expression must be non-dependant before "
15725 "building operator co_await");
15726 return Input;
15728 if (resultType.isNull() || Input.isInvalid())
15729 return ExprError();
15731 // Check for array bounds violations in the operand of the UnaryOperator,
15732 // except for the '*' and '&' operators that have to be handled specially
15733 // by CheckArrayAccess (as there are special cases like &array[arraysize]
15734 // that are explicitly defined as valid by the standard).
15735 if (Opc != UO_AddrOf && Opc != UO_Deref)
15736 CheckArrayAccess(Input.get());
15738 auto *UO =
15739 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15740 OpLoc, CanOverflow, CurFPFeatureOverrides());
15742 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15743 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15744 !isUnevaluatedContext())
15745 ExprEvalContexts.back().PossibleDerefs.insert(UO);
15747 // Convert the result back to a half vector.
15748 if (ConvertHalfVec)
15749 return convertVector(UO, Context.HalfTy, *this);
15750 return UO;
15753 /// Determine whether the given expression is a qualified member
15754 /// access expression, of a form that could be turned into a pointer to member
15755 /// with the address-of operator.
15756 bool Sema::isQualifiedMemberAccess(Expr *E) {
15757 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15758 if (!DRE->getQualifier())
15759 return false;
15761 ValueDecl *VD = DRE->getDecl();
15762 if (!VD->isCXXClassMember())
15763 return false;
15765 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15766 return true;
15767 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15768 return Method->isInstance();
15770 return false;
15773 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15774 if (!ULE->getQualifier())
15775 return false;
15777 for (NamedDecl *D : ULE->decls()) {
15778 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15779 if (Method->isInstance())
15780 return true;
15781 } else {
15782 // Overload set does not contain methods.
15783 break;
15787 return false;
15790 return false;
15793 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
15794 UnaryOperatorKind Opc, Expr *Input) {
15795 // First things first: handle placeholders so that the
15796 // overloaded-operator check considers the right type.
15797 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15798 // Increment and decrement of pseudo-object references.
15799 if (pty->getKind() == BuiltinType::PseudoObject &&
15800 UnaryOperator::isIncrementDecrementOp(Opc))
15801 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
15803 // extension is always a builtin operator.
15804 if (Opc == UO_Extension)
15805 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15807 // & gets special logic for several kinds of placeholder.
15808 // The builtin code knows what to do.
15809 if (Opc == UO_AddrOf &&
15810 (pty->getKind() == BuiltinType::Overload ||
15811 pty->getKind() == BuiltinType::UnknownAny ||
15812 pty->getKind() == BuiltinType::BoundMember))
15813 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15815 // Anything else needs to be handled now.
15816 ExprResult Result = CheckPlaceholderExpr(Input);
15817 if (Result.isInvalid()) return ExprError();
15818 Input = Result.get();
15821 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15822 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
15823 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15824 // Find all of the overloaded operators visible from this point.
15825 UnresolvedSet<16> Functions;
15826 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
15827 if (S && OverOp != OO_None)
15828 LookupOverloadedOperatorName(OverOp, S, Functions);
15830 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15833 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15836 // Unary Operators. 'Tok' is the token for the operator.
15837 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
15838 tok::TokenKind Op, Expr *Input) {
15839 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
15842 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
15843 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
15844 LabelDecl *TheDecl) {
15845 TheDecl->markUsed(Context);
15846 // Create the AST node. The address of a label always has type 'void*'.
15847 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
15848 Context.getPointerType(Context.VoidTy));
15851 void Sema::ActOnStartStmtExpr() {
15852 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15855 void Sema::ActOnStmtExprError() {
15856 // Note that function is also called by TreeTransform when leaving a
15857 // StmtExpr scope without rebuilding anything.
15859 DiscardCleanupsInEvaluationContext();
15860 PopExpressionEvaluationContext();
15863 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
15864 SourceLocation RPLoc) {
15865 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15868 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
15869 SourceLocation RPLoc, unsigned TemplateDepth) {
15870 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
15871 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15873 if (hasAnyUnrecoverableErrorsInThisFunction())
15874 DiscardCleanupsInEvaluationContext();
15875 assert(!Cleanup.exprNeedsCleanups() &&
15876 "cleanups within StmtExpr not correctly bound!");
15877 PopExpressionEvaluationContext();
15879 // FIXME: there are a variety of strange constraints to enforce here, for
15880 // example, it is not possible to goto into a stmt expression apparently.
15881 // More semantic analysis is needed.
15883 // If there are sub-stmts in the compound stmt, take the type of the last one
15884 // as the type of the stmtexpr.
15885 QualType Ty = Context.VoidTy;
15886 bool StmtExprMayBindToTemp = false;
15887 if (!Compound->body_empty()) {
15888 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15889 if (const auto *LastStmt =
15890 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15891 if (const Expr *Value = LastStmt->getExprStmt()) {
15892 StmtExprMayBindToTemp = true;
15893 Ty = Value->getType();
15898 // FIXME: Check that expression type is complete/non-abstract; statement
15899 // expressions are not lvalues.
15900 Expr *ResStmtExpr =
15901 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15902 if (StmtExprMayBindToTemp)
15903 return MaybeBindToTemporary(ResStmtExpr);
15904 return ResStmtExpr;
15907 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
15908 if (ER.isInvalid())
15909 return ExprError();
15911 // Do function/array conversion on the last expression, but not
15912 // lvalue-to-rvalue. However, initialize an unqualified type.
15913 ER = DefaultFunctionArrayConversion(ER.get());
15914 if (ER.isInvalid())
15915 return ExprError();
15916 Expr *E = ER.get();
15918 if (E->isTypeDependent())
15919 return E;
15921 // In ARC, if the final expression ends in a consume, splice
15922 // the consume out and bind it later. In the alternate case
15923 // (when dealing with a retainable type), the result
15924 // initialization will create a produce. In both cases the
15925 // result will be +1, and we'll need to balance that out with
15926 // a bind.
15927 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15928 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15929 return Cast->getSubExpr();
15931 // FIXME: Provide a better location for the initialization.
15932 return PerformCopyInitialization(
15933 InitializedEntity::InitializeStmtExprResult(
15934 E->getBeginLoc(), E->getType().getUnqualifiedType()),
15935 SourceLocation(), E);
15938 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
15939 TypeSourceInfo *TInfo,
15940 ArrayRef<OffsetOfComponent> Components,
15941 SourceLocation RParenLoc) {
15942 QualType ArgTy = TInfo->getType();
15943 bool Dependent = ArgTy->isDependentType();
15944 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15946 // We must have at least one component that refers to the type, and the first
15947 // one is known to be a field designator. Verify that the ArgTy represents
15948 // a struct/union/class.
15949 if (!Dependent && !ArgTy->isRecordType())
15950 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15951 << ArgTy << TypeRange);
15953 // Type must be complete per C99 7.17p3 because a declaring a variable
15954 // with an incomplete type would be ill-formed.
15955 if (!Dependent
15956 && RequireCompleteType(BuiltinLoc, ArgTy,
15957 diag::err_offsetof_incomplete_type, TypeRange))
15958 return ExprError();
15960 bool DidWarnAboutNonPOD = false;
15961 QualType CurrentType = ArgTy;
15962 SmallVector<OffsetOfNode, 4> Comps;
15963 SmallVector<Expr*, 4> Exprs;
15964 for (const OffsetOfComponent &OC : Components) {
15965 if (OC.isBrackets) {
15966 // Offset of an array sub-field. TODO: Should we allow vector elements?
15967 if (!CurrentType->isDependentType()) {
15968 const ArrayType *AT = Context.getAsArrayType(CurrentType);
15969 if(!AT)
15970 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15971 << CurrentType);
15972 CurrentType = AT->getElementType();
15973 } else
15974 CurrentType = Context.DependentTy;
15976 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15977 if (IdxRval.isInvalid())
15978 return ExprError();
15979 Expr *Idx = IdxRval.get();
15981 // The expression must be an integral expression.
15982 // FIXME: An integral constant expression?
15983 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15984 !Idx->getType()->isIntegerType())
15985 return ExprError(
15986 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15987 << Idx->getSourceRange());
15989 // Record this array index.
15990 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15991 Exprs.push_back(Idx);
15992 continue;
15995 // Offset of a field.
15996 if (CurrentType->isDependentType()) {
15997 // We have the offset of a field, but we can't look into the dependent
15998 // type. Just record the identifier of the field.
15999 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16000 CurrentType = Context.DependentTy;
16001 continue;
16004 // We need to have a complete type to look into.
16005 if (RequireCompleteType(OC.LocStart, CurrentType,
16006 diag::err_offsetof_incomplete_type))
16007 return ExprError();
16009 // Look for the designated field.
16010 const RecordType *RC = CurrentType->getAs<RecordType>();
16011 if (!RC)
16012 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16013 << CurrentType);
16014 RecordDecl *RD = RC->getDecl();
16016 // C++ [lib.support.types]p5:
16017 // The macro offsetof accepts a restricted set of type arguments in this
16018 // International Standard. type shall be a POD structure or a POD union
16019 // (clause 9).
16020 // C++11 [support.types]p4:
16021 // If type is not a standard-layout class (Clause 9), the results are
16022 // undefined.
16023 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16024 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16025 unsigned DiagID =
16026 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16027 : diag::ext_offsetof_non_pod_type;
16029 if (!IsSafe && !DidWarnAboutNonPOD &&
16030 DiagRuntimeBehavior(BuiltinLoc, nullptr,
16031 PDiag(DiagID)
16032 << SourceRange(Components[0].LocStart, OC.LocEnd)
16033 << CurrentType))
16034 DidWarnAboutNonPOD = true;
16037 // Look for the field.
16038 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16039 LookupQualifiedName(R, RD);
16040 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16041 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16042 if (!MemberDecl) {
16043 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16044 MemberDecl = IndirectMemberDecl->getAnonField();
16047 if (!MemberDecl)
16048 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
16049 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
16050 OC.LocEnd));
16052 // C99 7.17p3:
16053 // (If the specified member is a bit-field, the behavior is undefined.)
16055 // We diagnose this as an error.
16056 if (MemberDecl->isBitField()) {
16057 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16058 << MemberDecl->getDeclName()
16059 << SourceRange(BuiltinLoc, RParenLoc);
16060 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16061 return ExprError();
16064 RecordDecl *Parent = MemberDecl->getParent();
16065 if (IndirectMemberDecl)
16066 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16068 // If the member was found in a base class, introduce OffsetOfNodes for
16069 // the base class indirections.
16070 CXXBasePaths Paths;
16071 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
16072 Paths)) {
16073 if (Paths.getDetectedVirtual()) {
16074 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16075 << MemberDecl->getDeclName()
16076 << SourceRange(BuiltinLoc, RParenLoc);
16077 return ExprError();
16080 CXXBasePath &Path = Paths.front();
16081 for (const CXXBasePathElement &B : Path)
16082 Comps.push_back(OffsetOfNode(B.Base));
16085 if (IndirectMemberDecl) {
16086 for (auto *FI : IndirectMemberDecl->chain()) {
16087 assert(isa<FieldDecl>(FI));
16088 Comps.push_back(OffsetOfNode(OC.LocStart,
16089 cast<FieldDecl>(FI), OC.LocEnd));
16091 } else
16092 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16094 CurrentType = MemberDecl->getType().getNonReferenceType();
16097 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16098 Comps, Exprs, RParenLoc);
16101 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
16102 SourceLocation BuiltinLoc,
16103 SourceLocation TypeLoc,
16104 ParsedType ParsedArgTy,
16105 ArrayRef<OffsetOfComponent> Components,
16106 SourceLocation RParenLoc) {
16108 TypeSourceInfo *ArgTInfo;
16109 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16110 if (ArgTy.isNull())
16111 return ExprError();
16113 if (!ArgTInfo)
16114 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16116 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16120 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
16121 Expr *CondExpr,
16122 Expr *LHSExpr, Expr *RHSExpr,
16123 SourceLocation RPLoc) {
16124 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16126 ExprValueKind VK = VK_PRValue;
16127 ExprObjectKind OK = OK_Ordinary;
16128 QualType resType;
16129 bool CondIsTrue = false;
16130 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16131 resType = Context.DependentTy;
16132 } else {
16133 // The conditional expression is required to be a constant expression.
16134 llvm::APSInt condEval(32);
16135 ExprResult CondICE = VerifyIntegerConstantExpression(
16136 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16137 if (CondICE.isInvalid())
16138 return ExprError();
16139 CondExpr = CondICE.get();
16140 CondIsTrue = condEval.getZExtValue();
16142 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16143 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16145 resType = ActiveExpr->getType();
16146 VK = ActiveExpr->getValueKind();
16147 OK = ActiveExpr->getObjectKind();
16150 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16151 resType, VK, OK, RPLoc, CondIsTrue);
16154 //===----------------------------------------------------------------------===//
16155 // Clang Extensions.
16156 //===----------------------------------------------------------------------===//
16158 /// ActOnBlockStart - This callback is invoked when a block literal is started.
16159 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16160 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
16162 if (LangOpts.CPlusPlus) {
16163 MangleNumberingContext *MCtx;
16164 Decl *ManglingContextDecl;
16165 std::tie(MCtx, ManglingContextDecl) =
16166 getCurrentMangleNumberContext(Block->getDeclContext());
16167 if (MCtx) {
16168 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16169 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16173 PushBlockScope(CurScope, Block);
16174 CurContext->addDecl(Block);
16175 if (CurScope)
16176 PushDeclContext(CurScope, Block);
16177 else
16178 CurContext = Block;
16180 getCurBlock()->HasImplicitReturnType = true;
16182 // Enter a new evaluation context to insulate the block from any
16183 // cleanups from the enclosing full-expression.
16184 PushExpressionEvaluationContext(
16185 ExpressionEvaluationContext::PotentiallyEvaluated);
16188 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
16189 Scope *CurScope) {
16190 assert(ParamInfo.getIdentifier() == nullptr &&
16191 "block-id should have no identifier!");
16192 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16193 BlockScopeInfo *CurBlock = getCurBlock();
16195 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
16196 QualType T = Sig->getType();
16198 // FIXME: We should allow unexpanded parameter packs here, but that would,
16199 // in turn, make the block expression contain unexpanded parameter packs.
16200 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
16201 // Drop the parameters.
16202 FunctionProtoType::ExtProtoInfo EPI;
16203 EPI.HasTrailingReturn = false;
16204 EPI.TypeQuals.addConst();
16205 T = Context.getFunctionType(Context.DependentTy, None, EPI);
16206 Sig = Context.getTrivialTypeSourceInfo(T);
16209 // GetTypeForDeclarator always produces a function type for a block
16210 // literal signature. Furthermore, it is always a FunctionProtoType
16211 // unless the function was written with a typedef.
16212 assert(T->isFunctionType() &&
16213 "GetTypeForDeclarator made a non-function block signature");
16215 // Look for an explicit signature in that function type.
16216 FunctionProtoTypeLoc ExplicitSignature;
16218 if ((ExplicitSignature = Sig->getTypeLoc()
16219 .getAsAdjusted<FunctionProtoTypeLoc>())) {
16221 // Check whether that explicit signature was synthesized by
16222 // GetTypeForDeclarator. If so, don't save that as part of the
16223 // written signature.
16224 if (ExplicitSignature.getLocalRangeBegin() ==
16225 ExplicitSignature.getLocalRangeEnd()) {
16226 // This would be much cheaper if we stored TypeLocs instead of
16227 // TypeSourceInfos.
16228 TypeLoc Result = ExplicitSignature.getReturnLoc();
16229 unsigned Size = Result.getFullDataSize();
16230 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16231 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16233 ExplicitSignature = FunctionProtoTypeLoc();
16237 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16238 CurBlock->FunctionType = T;
16240 const auto *Fn = T->castAs<FunctionType>();
16241 QualType RetTy = Fn->getReturnType();
16242 bool isVariadic =
16243 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16245 CurBlock->TheDecl->setIsVariadic(isVariadic);
16247 // Context.DependentTy is used as a placeholder for a missing block
16248 // return type. TODO: what should we do with declarators like:
16249 // ^ * { ... }
16250 // If the answer is "apply template argument deduction"....
16251 if (RetTy != Context.DependentTy) {
16252 CurBlock->ReturnType = RetTy;
16253 CurBlock->TheDecl->setBlockMissingReturnType(false);
16254 CurBlock->HasImplicitReturnType = false;
16257 // Push block parameters from the declarator if we had them.
16258 SmallVector<ParmVarDecl*, 8> Params;
16259 if (ExplicitSignature) {
16260 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16261 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16262 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16263 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16264 // Diagnose this as an extension in C17 and earlier.
16265 if (!getLangOpts().C2x)
16266 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
16268 Params.push_back(Param);
16271 // Fake up parameter variables if we have a typedef, like
16272 // ^ fntype { ... }
16273 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16274 for (const auto &I : Fn->param_types()) {
16275 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
16276 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16277 Params.push_back(Param);
16281 // Set the parameters on the block decl.
16282 if (!Params.empty()) {
16283 CurBlock->TheDecl->setParams(Params);
16284 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
16285 /*CheckParameterNames=*/false);
16288 // Finally we can process decl attributes.
16289 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16291 // Put the parameter variables in scope.
16292 for (auto *AI : CurBlock->TheDecl->parameters()) {
16293 AI->setOwningFunction(CurBlock->TheDecl);
16295 // If this has an identifier, add it to the scope stack.
16296 if (AI->getIdentifier()) {
16297 CheckShadow(CurBlock->TheScope, AI);
16299 PushOnScopeChains(AI, CurBlock->TheScope);
16304 /// ActOnBlockError - If there is an error parsing a block, this callback
16305 /// is invoked to pop the information about the block from the action impl.
16306 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16307 // Leave the expression-evaluation context.
16308 DiscardCleanupsInEvaluationContext();
16309 PopExpressionEvaluationContext();
16311 // Pop off CurBlock, handle nested blocks.
16312 PopDeclContext();
16313 PopFunctionScopeInfo();
16316 /// ActOnBlockStmtExpr - This is called when the body of a block statement
16317 /// literal was successfully completed. ^(int x){...}
16318 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
16319 Stmt *Body, Scope *CurScope) {
16320 // If blocks are disabled, emit an error.
16321 if (!LangOpts.Blocks)
16322 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16324 // Leave the expression-evaluation context.
16325 if (hasAnyUnrecoverableErrorsInThisFunction())
16326 DiscardCleanupsInEvaluationContext();
16327 assert(!Cleanup.exprNeedsCleanups() &&
16328 "cleanups within block not correctly bound!");
16329 PopExpressionEvaluationContext();
16331 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16332 BlockDecl *BD = BSI->TheDecl;
16334 if (BSI->HasImplicitReturnType)
16335 deduceClosureReturnType(*BSI);
16337 QualType RetTy = Context.VoidTy;
16338 if (!BSI->ReturnType.isNull())
16339 RetTy = BSI->ReturnType;
16341 bool NoReturn = BD->hasAttr<NoReturnAttr>();
16342 QualType BlockTy;
16344 // If the user wrote a function type in some form, try to use that.
16345 if (!BSI->FunctionType.isNull()) {
16346 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16348 FunctionType::ExtInfo Ext = FTy->getExtInfo();
16349 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16351 // Turn protoless block types into nullary block types.
16352 if (isa<FunctionNoProtoType>(FTy)) {
16353 FunctionProtoType::ExtProtoInfo EPI;
16354 EPI.ExtInfo = Ext;
16355 BlockTy = Context.getFunctionType(RetTy, None, EPI);
16357 // Otherwise, if we don't need to change anything about the function type,
16358 // preserve its sugar structure.
16359 } else if (FTy->getReturnType() == RetTy &&
16360 (!NoReturn || FTy->getNoReturnAttr())) {
16361 BlockTy = BSI->FunctionType;
16363 // Otherwise, make the minimal modifications to the function type.
16364 } else {
16365 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16366 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
16367 EPI.TypeQuals = Qualifiers();
16368 EPI.ExtInfo = Ext;
16369 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16372 // If we don't have a function type, just build one from nothing.
16373 } else {
16374 FunctionProtoType::ExtProtoInfo EPI;
16375 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16376 BlockTy = Context.getFunctionType(RetTy, None, EPI);
16379 DiagnoseUnusedParameters(BD->parameters());
16380 BlockTy = Context.getBlockPointerType(BlockTy);
16382 // If needed, diagnose invalid gotos and switches in the block.
16383 if (getCurFunction()->NeedsScopeChecking() &&
16384 !PP.isCodeCompletionEnabled())
16385 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16387 BD->setBody(cast<CompoundStmt>(Body));
16389 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16390 DiagnoseUnguardedAvailabilityViolations(BD);
16392 // Try to apply the named return value optimization. We have to check again
16393 // if we can do this, though, because blocks keep return statements around
16394 // to deduce an implicit return type.
16395 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16396 !BD->isDependentContext())
16397 computeNRVO(Body, BSI);
16399 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
16400 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
16401 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
16402 NTCUK_Destruct|NTCUK_Copy);
16404 PopDeclContext();
16406 // Set the captured variables on the block.
16407 SmallVector<BlockDecl::Capture, 4> Captures;
16408 for (Capture &Cap : BSI->Captures) {
16409 if (Cap.isInvalid() || Cap.isThisCapture())
16410 continue;
16411 // Cap.getVariable() is always a VarDecl because
16412 // blocks cannot capture structured bindings or other ValueDecl kinds.
16413 auto *Var = cast<VarDecl>(Cap.getVariable());
16414 Expr *CopyExpr = nullptr;
16415 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16416 if (const RecordType *Record =
16417 Cap.getCaptureType()->getAs<RecordType>()) {
16418 // The capture logic needs the destructor, so make sure we mark it.
16419 // Usually this is unnecessary because most local variables have
16420 // their destructors marked at declaration time, but parameters are
16421 // an exception because it's technically only the call site that
16422 // actually requires the destructor.
16423 if (isa<ParmVarDecl>(Var))
16424 FinalizeVarWithDestructor(Var, Record);
16426 // Enter a separate potentially-evaluated context while building block
16427 // initializers to isolate their cleanups from those of the block
16428 // itself.
16429 // FIXME: Is this appropriate even when the block itself occurs in an
16430 // unevaluated operand?
16431 EnterExpressionEvaluationContext EvalContext(
16432 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16434 SourceLocation Loc = Cap.getLocation();
16436 ExprResult Result = BuildDeclarationNameExpr(
16437 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16439 // According to the blocks spec, the capture of a variable from
16440 // the stack requires a const copy constructor. This is not true
16441 // of the copy/move done to move a __block variable to the heap.
16442 if (!Result.isInvalid() &&
16443 !Result.get()->getType().isConstQualified()) {
16444 Result = ImpCastExprToType(Result.get(),
16445 Result.get()->getType().withConst(),
16446 CK_NoOp, VK_LValue);
16449 if (!Result.isInvalid()) {
16450 Result = PerformCopyInitialization(
16451 InitializedEntity::InitializeBlock(Var->getLocation(),
16452 Cap.getCaptureType()),
16453 Loc, Result.get());
16456 // Build a full-expression copy expression if initialization
16457 // succeeded and used a non-trivial constructor. Recover from
16458 // errors by pretending that the copy isn't necessary.
16459 if (!Result.isInvalid() &&
16460 !cast<CXXConstructExpr>(Result.get())->getConstructor()
16461 ->isTrivial()) {
16462 Result = MaybeCreateExprWithCleanups(Result);
16463 CopyExpr = Result.get();
16468 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16469 CopyExpr);
16470 Captures.push_back(NewCap);
16472 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16474 // Pop the block scope now but keep it alive to the end of this function.
16475 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
16476 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16478 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
16480 // If the block isn't obviously global, i.e. it captures anything at
16481 // all, then we need to do a few things in the surrounding context:
16482 if (Result->getBlockDecl()->hasCaptures()) {
16483 // First, this expression has a new cleanup object.
16484 ExprCleanupObjects.push_back(Result->getBlockDecl());
16485 Cleanup.setExprNeedsCleanups(true);
16487 // It also gets a branch-protected scope if any of the captured
16488 // variables needs destruction.
16489 for (const auto &CI : Result->getBlockDecl()->captures()) {
16490 const VarDecl *var = CI.getVariable();
16491 if (var->getType().isDestructedType() != QualType::DK_none) {
16492 setFunctionHasBranchProtectedScope();
16493 break;
16498 if (getCurFunction())
16499 getCurFunction()->addBlock(BD);
16501 return Result;
16504 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
16505 SourceLocation RPLoc) {
16506 TypeSourceInfo *TInfo;
16507 GetTypeFromParser(Ty, &TInfo);
16508 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16511 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
16512 Expr *E, TypeSourceInfo *TInfo,
16513 SourceLocation RPLoc) {
16514 Expr *OrigExpr = E;
16515 bool IsMS = false;
16517 // CUDA device code does not support varargs.
16518 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16519 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16520 CUDAFunctionTarget T = IdentifyCUDATarget(F);
16521 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
16522 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16526 // NVPTX does not support va_arg expression.
16527 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
16528 Context.getTargetInfo().getTriple().isNVPTX())
16529 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16531 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16532 // as Microsoft ABI on an actual Microsoft platform, where
16533 // __builtin_ms_va_list and __builtin_va_list are the same.)
16534 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
16535 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
16536 QualType MSVaListType = Context.getBuiltinMSVaListType();
16537 if (Context.hasSameType(MSVaListType, E->getType())) {
16538 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16539 return ExprError();
16540 IsMS = true;
16544 // Get the va_list type
16545 QualType VaListType = Context.getBuiltinVaListType();
16546 if (!IsMS) {
16547 if (VaListType->isArrayType()) {
16548 // Deal with implicit array decay; for example, on x86-64,
16549 // va_list is an array, but it's supposed to decay to
16550 // a pointer for va_arg.
16551 VaListType = Context.getArrayDecayedType(VaListType);
16552 // Make sure the input expression also decays appropriately.
16553 ExprResult Result = UsualUnaryConversions(E);
16554 if (Result.isInvalid())
16555 return ExprError();
16556 E = Result.get();
16557 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16558 // If va_list is a record type and we are compiling in C++ mode,
16559 // check the argument using reference binding.
16560 InitializedEntity Entity = InitializedEntity::InitializeParameter(
16561 Context, Context.getLValueReferenceType(VaListType), false);
16562 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
16563 if (Init.isInvalid())
16564 return ExprError();
16565 E = Init.getAs<Expr>();
16566 } else {
16567 // Otherwise, the va_list argument must be an l-value because
16568 // it is modified by va_arg.
16569 if (!E->isTypeDependent() &&
16570 CheckForModifiableLvalue(E, BuiltinLoc, *this))
16571 return ExprError();
16575 if (!IsMS && !E->isTypeDependent() &&
16576 !Context.hasSameType(VaListType, E->getType()))
16577 return ExprError(
16578 Diag(E->getBeginLoc(),
16579 diag::err_first_argument_to_va_arg_not_of_type_va_list)
16580 << OrigExpr->getType() << E->getSourceRange());
16582 if (!TInfo->getType()->isDependentType()) {
16583 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16584 diag::err_second_parameter_to_va_arg_incomplete,
16585 TInfo->getTypeLoc()))
16586 return ExprError();
16588 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
16589 TInfo->getType(),
16590 diag::err_second_parameter_to_va_arg_abstract,
16591 TInfo->getTypeLoc()))
16592 return ExprError();
16594 if (!TInfo->getType().isPODType(Context)) {
16595 Diag(TInfo->getTypeLoc().getBeginLoc(),
16596 TInfo->getType()->isObjCLifetimeType()
16597 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16598 : diag::warn_second_parameter_to_va_arg_not_pod)
16599 << TInfo->getType()
16600 << TInfo->getTypeLoc().getSourceRange();
16603 // Check for va_arg where arguments of the given type will be promoted
16604 // (i.e. this va_arg is guaranteed to have undefined behavior).
16605 QualType PromoteType;
16606 if (TInfo->getType()->isPromotableIntegerType()) {
16607 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16608 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16609 // and C2x 7.16.1.1p2 says, in part:
16610 // If type is not compatible with the type of the actual next argument
16611 // (as promoted according to the default argument promotions), the
16612 // behavior is undefined, except for the following cases:
16613 // - both types are pointers to qualified or unqualified versions of
16614 // compatible types;
16615 // - one type is a signed integer type, the other type is the
16616 // corresponding unsigned integer type, and the value is
16617 // representable in both types;
16618 // - one type is pointer to qualified or unqualified void and the
16619 // other is a pointer to a qualified or unqualified character type.
16620 // Given that type compatibility is the primary requirement (ignoring
16621 // qualifications), you would think we could call typesAreCompatible()
16622 // directly to test this. However, in C++, that checks for *same type*,
16623 // which causes false positives when passing an enumeration type to
16624 // va_arg. Instead, get the underlying type of the enumeration and pass
16625 // that.
16626 QualType UnderlyingType = TInfo->getType();
16627 if (const auto *ET = UnderlyingType->getAs<EnumType>())
16628 UnderlyingType = ET->getDecl()->getIntegerType();
16629 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16630 /*CompareUnqualified*/ true))
16631 PromoteType = QualType();
16633 // If the types are still not compatible, we need to test whether the
16634 // promoted type and the underlying type are the same except for
16635 // signedness. Ask the AST for the correctly corresponding type and see
16636 // if that's compatible.
16637 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16638 PromoteType->isUnsignedIntegerType() !=
16639 UnderlyingType->isUnsignedIntegerType()) {
16640 UnderlyingType =
16641 UnderlyingType->isUnsignedIntegerType()
16642 ? Context.getCorrespondingSignedType(UnderlyingType)
16643 : Context.getCorrespondingUnsignedType(UnderlyingType);
16644 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16645 /*CompareUnqualified*/ true))
16646 PromoteType = QualType();
16649 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16650 PromoteType = Context.DoubleTy;
16651 if (!PromoteType.isNull())
16652 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
16653 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16654 << TInfo->getType()
16655 << PromoteType
16656 << TInfo->getTypeLoc().getSourceRange());
16659 QualType T = TInfo->getType().getNonLValueExprType(Context);
16660 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16663 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
16664 // The type of __null will be int or long, depending on the size of
16665 // pointers on the target.
16666 QualType Ty;
16667 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
16668 if (pw == Context.getTargetInfo().getIntWidth())
16669 Ty = Context.IntTy;
16670 else if (pw == Context.getTargetInfo().getLongWidth())
16671 Ty = Context.LongTy;
16672 else if (pw == Context.getTargetInfo().getLongLongWidth())
16673 Ty = Context.LongLongTy;
16674 else {
16675 llvm_unreachable("I don't know size of pointer!");
16678 return new (Context) GNUNullExpr(Ty, TokenLoc);
16681 static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
16682 CXXRecordDecl *ImplDecl = nullptr;
16684 // Fetch the std::source_location::__impl decl.
16685 if (NamespaceDecl *Std = S.getStdNamespace()) {
16686 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
16687 Loc, Sema::LookupOrdinaryName);
16688 if (S.LookupQualifiedName(ResultSL, Std)) {
16689 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
16690 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
16691 Loc, Sema::LookupOrdinaryName);
16692 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
16693 S.LookupQualifiedName(ResultImpl, SLDecl)) {
16694 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
16700 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
16701 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
16702 return nullptr;
16705 // Verify that __impl is a trivial struct type, with no base classes, and with
16706 // only the four expected fields.
16707 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
16708 ImplDecl->getNumBases() != 0) {
16709 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16710 return nullptr;
16713 unsigned Count = 0;
16714 for (FieldDecl *F : ImplDecl->fields()) {
16715 StringRef Name = F->getName();
16717 if (Name == "_M_file_name") {
16718 if (F->getType() !=
16719 S.Context.getPointerType(S.Context.CharTy.withConst()))
16720 break;
16721 Count++;
16722 } else if (Name == "_M_function_name") {
16723 if (F->getType() !=
16724 S.Context.getPointerType(S.Context.CharTy.withConst()))
16725 break;
16726 Count++;
16727 } else if (Name == "_M_line") {
16728 if (!F->getType()->isIntegerType())
16729 break;
16730 Count++;
16731 } else if (Name == "_M_column") {
16732 if (!F->getType()->isIntegerType())
16733 break;
16734 Count++;
16735 } else {
16736 Count = 100; // invalid
16737 break;
16740 if (Count != 4) {
16741 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16742 return nullptr;
16745 return ImplDecl;
16748 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
16749 SourceLocation BuiltinLoc,
16750 SourceLocation RPLoc) {
16751 QualType ResultTy;
16752 switch (Kind) {
16753 case SourceLocExpr::File:
16754 case SourceLocExpr::Function: {
16755 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
16756 ResultTy =
16757 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
16758 break;
16760 case SourceLocExpr::Line:
16761 case SourceLocExpr::Column:
16762 ResultTy = Context.UnsignedIntTy;
16763 break;
16764 case SourceLocExpr::SourceLocStruct:
16765 if (!StdSourceLocationImplDecl) {
16766 StdSourceLocationImplDecl =
16767 LookupStdSourceLocationImpl(*this, BuiltinLoc);
16768 if (!StdSourceLocationImplDecl)
16769 return ExprError();
16771 ResultTy = Context.getPointerType(
16772 Context.getRecordType(StdSourceLocationImplDecl).withConst());
16773 break;
16776 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
16779 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
16780 QualType ResultTy,
16781 SourceLocation BuiltinLoc,
16782 SourceLocation RPLoc,
16783 DeclContext *ParentContext) {
16784 return new (Context)
16785 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
16788 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
16789 bool Diagnose) {
16790 if (!getLangOpts().ObjC)
16791 return false;
16793 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
16794 if (!PT)
16795 return false;
16796 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
16798 // Ignore any parens, implicit casts (should only be
16799 // array-to-pointer decays), and not-so-opaque values. The last is
16800 // important for making this trigger for property assignments.
16801 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
16802 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
16803 if (OV->getSourceExpr())
16804 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
16806 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
16807 if (!PT->isObjCIdType() &&
16808 !(ID && ID->getIdentifier()->isStr("NSString")))
16809 return false;
16810 if (!SL->isOrdinary())
16811 return false;
16813 if (Diagnose) {
16814 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
16815 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
16816 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
16818 return true;
16821 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
16822 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
16823 isa<CXXBoolLiteralExpr>(SrcExpr)) &&
16824 !SrcExpr->isNullPointerConstant(
16825 getASTContext(), Expr::NPC_NeverValueDependent)) {
16826 if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
16827 return false;
16828 if (Diagnose) {
16829 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
16830 << /*number*/1
16831 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
16832 Expr *NumLit =
16833 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
16834 if (NumLit)
16835 Exp = NumLit;
16837 return true;
16840 return false;
16843 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
16844 const Expr *SrcExpr) {
16845 if (!DstType->isFunctionPointerType() ||
16846 !SrcExpr->getType()->isFunctionType())
16847 return false;
16849 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
16850 if (!DRE)
16851 return false;
16853 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
16854 if (!FD)
16855 return false;
16857 return !S.checkAddressOfFunctionIsAvailable(FD,
16858 /*Complain=*/true,
16859 SrcExpr->getBeginLoc());
16862 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
16863 SourceLocation Loc,
16864 QualType DstType, QualType SrcType,
16865 Expr *SrcExpr, AssignmentAction Action,
16866 bool *Complained) {
16867 if (Complained)
16868 *Complained = false;
16870 // Decode the result (notice that AST's are still created for extensions).
16871 bool CheckInferredResultType = false;
16872 bool isInvalid = false;
16873 unsigned DiagKind = 0;
16874 ConversionFixItGenerator ConvHints;
16875 bool MayHaveConvFixit = false;
16876 bool MayHaveFunctionDiff = false;
16877 const ObjCInterfaceDecl *IFace = nullptr;
16878 const ObjCProtocolDecl *PDecl = nullptr;
16880 switch (ConvTy) {
16881 case Compatible:
16882 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16883 return false;
16885 case PointerToInt:
16886 if (getLangOpts().CPlusPlus) {
16887 DiagKind = diag::err_typecheck_convert_pointer_int;
16888 isInvalid = true;
16889 } else {
16890 DiagKind = diag::ext_typecheck_convert_pointer_int;
16892 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16893 MayHaveConvFixit = true;
16894 break;
16895 case IntToPointer:
16896 if (getLangOpts().CPlusPlus) {
16897 DiagKind = diag::err_typecheck_convert_int_pointer;
16898 isInvalid = true;
16899 } else {
16900 DiagKind = diag::ext_typecheck_convert_int_pointer;
16902 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16903 MayHaveConvFixit = true;
16904 break;
16905 case IncompatibleFunctionPointer:
16906 if (getLangOpts().CPlusPlus) {
16907 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16908 isInvalid = true;
16909 } else {
16910 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16912 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16913 MayHaveConvFixit = true;
16914 break;
16915 case IncompatiblePointer:
16916 if (Action == AA_Passing_CFAudited) {
16917 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16918 } else if (getLangOpts().CPlusPlus) {
16919 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16920 isInvalid = true;
16921 } else {
16922 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16924 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16925 SrcType->isObjCObjectPointerType();
16926 if (!CheckInferredResultType) {
16927 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16928 } else if (CheckInferredResultType) {
16929 SrcType = SrcType.getUnqualifiedType();
16930 DstType = DstType.getUnqualifiedType();
16932 MayHaveConvFixit = true;
16933 break;
16934 case IncompatiblePointerSign:
16935 if (getLangOpts().CPlusPlus) {
16936 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16937 isInvalid = true;
16938 } else {
16939 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16941 break;
16942 case FunctionVoidPointer:
16943 if (getLangOpts().CPlusPlus) {
16944 DiagKind = diag::err_typecheck_convert_pointer_void_func;
16945 isInvalid = true;
16946 } else {
16947 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16949 break;
16950 case IncompatiblePointerDiscardsQualifiers: {
16951 // Perform array-to-pointer decay if necessary.
16952 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16954 isInvalid = true;
16956 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16957 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16958 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16959 DiagKind = diag::err_typecheck_incompatible_address_space;
16960 break;
16962 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16963 DiagKind = diag::err_typecheck_incompatible_ownership;
16964 break;
16967 llvm_unreachable("unknown error case for discarding qualifiers!");
16968 // fallthrough
16970 case CompatiblePointerDiscardsQualifiers:
16971 // If the qualifiers lost were because we were applying the
16972 // (deprecated) C++ conversion from a string literal to a char*
16973 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
16974 // Ideally, this check would be performed in
16975 // checkPointerTypesForAssignment. However, that would require a
16976 // bit of refactoring (so that the second argument is an
16977 // expression, rather than a type), which should be done as part
16978 // of a larger effort to fix checkPointerTypesForAssignment for
16979 // C++ semantics.
16980 if (getLangOpts().CPlusPlus &&
16981 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
16982 return false;
16983 if (getLangOpts().CPlusPlus) {
16984 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
16985 isInvalid = true;
16986 } else {
16987 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
16990 break;
16991 case IncompatibleNestedPointerQualifiers:
16992 if (getLangOpts().CPlusPlus) {
16993 isInvalid = true;
16994 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16995 } else {
16996 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16998 break;
16999 case IncompatibleNestedPointerAddressSpaceMismatch:
17000 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17001 isInvalid = true;
17002 break;
17003 case IntToBlockPointer:
17004 DiagKind = diag::err_int_to_block_pointer;
17005 isInvalid = true;
17006 break;
17007 case IncompatibleBlockPointer:
17008 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17009 isInvalid = true;
17010 break;
17011 case IncompatibleObjCQualifiedId: {
17012 if (SrcType->isObjCQualifiedIdType()) {
17013 const ObjCObjectPointerType *srcOPT =
17014 SrcType->castAs<ObjCObjectPointerType>();
17015 for (auto *srcProto : srcOPT->quals()) {
17016 PDecl = srcProto;
17017 break;
17019 if (const ObjCInterfaceType *IFaceT =
17020 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17021 IFace = IFaceT->getDecl();
17023 else if (DstType->isObjCQualifiedIdType()) {
17024 const ObjCObjectPointerType *dstOPT =
17025 DstType->castAs<ObjCObjectPointerType>();
17026 for (auto *dstProto : dstOPT->quals()) {
17027 PDecl = dstProto;
17028 break;
17030 if (const ObjCInterfaceType *IFaceT =
17031 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
17032 IFace = IFaceT->getDecl();
17034 if (getLangOpts().CPlusPlus) {
17035 DiagKind = diag::err_incompatible_qualified_id;
17036 isInvalid = true;
17037 } else {
17038 DiagKind = diag::warn_incompatible_qualified_id;
17040 break;
17042 case IncompatibleVectors:
17043 if (getLangOpts().CPlusPlus) {
17044 DiagKind = diag::err_incompatible_vectors;
17045 isInvalid = true;
17046 } else {
17047 DiagKind = diag::warn_incompatible_vectors;
17049 break;
17050 case IncompatibleObjCWeakRef:
17051 DiagKind = diag::err_arc_weak_unavailable_assign;
17052 isInvalid = true;
17053 break;
17054 case Incompatible:
17055 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17056 if (Complained)
17057 *Complained = true;
17058 return true;
17061 DiagKind = diag::err_typecheck_convert_incompatible;
17062 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17063 MayHaveConvFixit = true;
17064 isInvalid = true;
17065 MayHaveFunctionDiff = true;
17066 break;
17069 QualType FirstType, SecondType;
17070 switch (Action) {
17071 case AA_Assigning:
17072 case AA_Initializing:
17073 // The destination type comes first.
17074 FirstType = DstType;
17075 SecondType = SrcType;
17076 break;
17078 case AA_Returning:
17079 case AA_Passing:
17080 case AA_Passing_CFAudited:
17081 case AA_Converting:
17082 case AA_Sending:
17083 case AA_Casting:
17084 // The source type comes first.
17085 FirstType = SrcType;
17086 SecondType = DstType;
17087 break;
17090 PartialDiagnostic FDiag = PDiag(DiagKind);
17091 AssignmentAction ActionForDiag = Action;
17092 if (Action == AA_Passing_CFAudited)
17093 ActionForDiag = AA_Passing;
17095 FDiag << FirstType << SecondType << ActionForDiag
17096 << SrcExpr->getSourceRange();
17098 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17099 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17100 auto isPlainChar = [](const clang::Type *Type) {
17101 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17102 Type->isSpecificBuiltinType(BuiltinType::Char_U);
17104 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17105 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17108 // If we can fix the conversion, suggest the FixIts.
17109 if (!ConvHints.isNull()) {
17110 for (FixItHint &H : ConvHints.Hints)
17111 FDiag << H;
17114 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17116 if (MayHaveFunctionDiff)
17117 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17119 Diag(Loc, FDiag);
17120 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17121 DiagKind == diag::err_incompatible_qualified_id) &&
17122 PDecl && IFace && !IFace->hasDefinition())
17123 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17124 << IFace << PDecl;
17126 if (SecondType == Context.OverloadTy)
17127 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
17128 FirstType, /*TakingAddress=*/true);
17130 if (CheckInferredResultType)
17131 EmitRelatedResultTypeNote(SrcExpr);
17133 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
17134 EmitRelatedResultTypeNoteForReturn(DstType);
17136 if (Complained)
17137 *Complained = true;
17138 return isInvalid;
17141 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17142 llvm::APSInt *Result,
17143 AllowFoldKind CanFold) {
17144 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17145 public:
17146 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17147 QualType T) override {
17148 return S.Diag(Loc, diag::err_ice_not_integral)
17149 << T << S.LangOpts.CPlusPlus;
17151 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17152 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17154 } Diagnoser;
17156 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17159 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17160 llvm::APSInt *Result,
17161 unsigned DiagID,
17162 AllowFoldKind CanFold) {
17163 class IDDiagnoser : public VerifyICEDiagnoser {
17164 unsigned DiagID;
17166 public:
17167 IDDiagnoser(unsigned DiagID)
17168 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17170 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17171 return S.Diag(Loc, DiagID);
17173 } Diagnoser(DiagID);
17175 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17178 Sema::SemaDiagnosticBuilder
17179 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
17180 QualType T) {
17181 return diagnoseNotICE(S, Loc);
17184 Sema::SemaDiagnosticBuilder
17185 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
17186 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17189 ExprResult
17190 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
17191 VerifyICEDiagnoser &Diagnoser,
17192 AllowFoldKind CanFold) {
17193 SourceLocation DiagLoc = E->getBeginLoc();
17195 if (getLangOpts().CPlusPlus11) {
17196 // C++11 [expr.const]p5:
17197 // If an expression of literal class type is used in a context where an
17198 // integral constant expression is required, then that class type shall
17199 // have a single non-explicit conversion function to an integral or
17200 // unscoped enumeration type
17201 ExprResult Converted;
17202 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17203 VerifyICEDiagnoser &BaseDiagnoser;
17204 public:
17205 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17206 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17207 BaseDiagnoser.Suppress, true),
17208 BaseDiagnoser(BaseDiagnoser) {}
17210 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17211 QualType T) override {
17212 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17215 SemaDiagnosticBuilder diagnoseIncomplete(
17216 Sema &S, SourceLocation Loc, QualType T) override {
17217 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17220 SemaDiagnosticBuilder diagnoseExplicitConv(
17221 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17222 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17225 SemaDiagnosticBuilder noteExplicitConv(
17226 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17227 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17228 << ConvTy->isEnumeralType() << ConvTy;
17231 SemaDiagnosticBuilder diagnoseAmbiguous(
17232 Sema &S, SourceLocation Loc, QualType T) override {
17233 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17236 SemaDiagnosticBuilder noteAmbiguous(
17237 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17238 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17239 << ConvTy->isEnumeralType() << ConvTy;
17242 SemaDiagnosticBuilder diagnoseConversion(
17243 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17244 llvm_unreachable("conversion functions are permitted");
17246 } ConvertDiagnoser(Diagnoser);
17248 Converted = PerformContextualImplicitConversion(DiagLoc, E,
17249 ConvertDiagnoser);
17250 if (Converted.isInvalid())
17251 return Converted;
17252 E = Converted.get();
17253 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
17254 return ExprError();
17255 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17256 // An ICE must be of integral or unscoped enumeration type.
17257 if (!Diagnoser.Suppress)
17258 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17259 << E->getSourceRange();
17260 return ExprError();
17263 ExprResult RValueExpr = DefaultLvalueConversion(E);
17264 if (RValueExpr.isInvalid())
17265 return ExprError();
17267 E = RValueExpr.get();
17269 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17270 // in the non-ICE case.
17271 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
17272 if (Result)
17273 *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
17274 if (!isa<ConstantExpr>(E))
17275 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
17276 : ConstantExpr::Create(Context, E);
17277 return E;
17280 Expr::EvalResult EvalResult;
17281 SmallVector<PartialDiagnosticAt, 8> Notes;
17282 EvalResult.Diag = &Notes;
17284 // Try to evaluate the expression, and produce diagnostics explaining why it's
17285 // not a constant expression as a side-effect.
17286 bool Folded =
17287 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17288 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
17290 if (!isa<ConstantExpr>(E))
17291 E = ConstantExpr::Create(Context, E, EvalResult.Val);
17293 // In C++11, we can rely on diagnostics being produced for any expression
17294 // which is not a constant expression. If no diagnostics were produced, then
17295 // this is a constant expression.
17296 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17297 if (Result)
17298 *Result = EvalResult.Val.getInt();
17299 return E;
17302 // If our only note is the usual "invalid subexpression" note, just point
17303 // the caret at its location rather than producing an essentially
17304 // redundant note.
17305 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17306 diag::note_invalid_subexpr_in_const_expr) {
17307 DiagLoc = Notes[0].first;
17308 Notes.clear();
17311 if (!Folded || !CanFold) {
17312 if (!Diagnoser.Suppress) {
17313 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17314 for (const PartialDiagnosticAt &Note : Notes)
17315 Diag(Note.first, Note.second);
17318 return ExprError();
17321 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17322 for (const PartialDiagnosticAt &Note : Notes)
17323 Diag(Note.first, Note.second);
17325 if (Result)
17326 *Result = EvalResult.Val.getInt();
17327 return E;
17330 namespace {
17331 // Handle the case where we conclude a expression which we speculatively
17332 // considered to be unevaluated is actually evaluated.
17333 class TransformToPE : public TreeTransform<TransformToPE> {
17334 typedef TreeTransform<TransformToPE> BaseTransform;
17336 public:
17337 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17339 // Make sure we redo semantic analysis
17340 bool AlwaysRebuild() { return true; }
17341 bool ReplacingOriginal() { return true; }
17343 // We need to special-case DeclRefExprs referring to FieldDecls which
17344 // are not part of a member pointer formation; normal TreeTransforming
17345 // doesn't catch this case because of the way we represent them in the AST.
17346 // FIXME: This is a bit ugly; is it really the best way to handle this
17347 // case?
17349 // Error on DeclRefExprs referring to FieldDecls.
17350 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17351 if (isa<FieldDecl>(E->getDecl()) &&
17352 !SemaRef.isUnevaluatedContext())
17353 return SemaRef.Diag(E->getLocation(),
17354 diag::err_invalid_non_static_member_use)
17355 << E->getDecl() << E->getSourceRange();
17357 return BaseTransform::TransformDeclRefExpr(E);
17360 // Exception: filter out member pointer formation
17361 ExprResult TransformUnaryOperator(UnaryOperator *E) {
17362 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17363 return E;
17365 return BaseTransform::TransformUnaryOperator(E);
17368 // The body of a lambda-expression is in a separate expression evaluation
17369 // context so never needs to be transformed.
17370 // FIXME: Ideally we wouldn't transform the closure type either, and would
17371 // just recreate the capture expressions and lambda expression.
17372 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17373 return SkipLambdaBody(E, Body);
17378 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
17379 assert(isUnevaluatedContext() &&
17380 "Should only transform unevaluated expressions");
17381 ExprEvalContexts.back().Context =
17382 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17383 if (isUnevaluatedContext())
17384 return E;
17385 return TransformToPE(*this).TransformExpr(E);
17388 TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
17389 assert(isUnevaluatedContext() &&
17390 "Should only transform unevaluated expressions");
17391 ExprEvalContexts.back().Context =
17392 ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
17393 if (isUnevaluatedContext())
17394 return TInfo;
17395 return TransformToPE(*this).TransformType(TInfo);
17398 void
17399 Sema::PushExpressionEvaluationContext(
17400 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17401 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17402 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17403 LambdaContextDecl, ExprContext);
17405 // Discarded statements and immediate contexts nested in other
17406 // discarded statements or immediate context are themselves
17407 // a discarded statement or an immediate context, respectively.
17408 ExprEvalContexts.back().InDiscardedStatement =
17409 ExprEvalContexts[ExprEvalContexts.size() - 2]
17410 .isDiscardedStatementContext();
17411 ExprEvalContexts.back().InImmediateFunctionContext =
17412 ExprEvalContexts[ExprEvalContexts.size() - 2]
17413 .isImmediateFunctionContext();
17415 Cleanup.reset();
17416 if (!MaybeODRUseExprs.empty())
17417 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17420 void
17421 Sema::PushExpressionEvaluationContext(
17422 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
17423 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17424 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17425 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17428 namespace {
17430 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17431 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17432 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17433 if (E->getOpcode() == UO_Deref)
17434 return CheckPossibleDeref(S, E->getSubExpr());
17435 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17436 return CheckPossibleDeref(S, E->getBase());
17437 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17438 return CheckPossibleDeref(S, E->getBase());
17439 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17440 QualType Inner;
17441 QualType Ty = E->getType();
17442 if (const auto *Ptr = Ty->getAs<PointerType>())
17443 Inner = Ptr->getPointeeType();
17444 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17445 Inner = Arr->getElementType();
17446 else
17447 return nullptr;
17449 if (Inner->hasAttr(attr::NoDeref))
17450 return E;
17452 return nullptr;
17455 } // namespace
17457 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
17458 for (const Expr *E : Rec.PossibleDerefs) {
17459 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17460 if (DeclRef) {
17461 const ValueDecl *Decl = DeclRef->getDecl();
17462 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17463 << Decl->getName() << E->getSourceRange();
17464 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17465 } else {
17466 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17467 << E->getSourceRange();
17470 Rec.PossibleDerefs.clear();
17473 /// Check whether E, which is either a discarded-value expression or an
17474 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
17475 /// and if so, remove it from the list of volatile-qualified assignments that
17476 /// we are going to warn are deprecated.
17477 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
17478 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
17479 return;
17481 // Note: ignoring parens here is not justified by the standard rules, but
17482 // ignoring parentheses seems like a more reasonable approach, and this only
17483 // drives a deprecation warning so doesn't affect conformance.
17484 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17485 if (BO->getOpcode() == BO_Assign) {
17486 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17487 llvm::erase_value(LHSs, BO->getLHS());
17492 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
17493 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17494 !Decl->isConsteval() || isConstantEvaluated() ||
17495 RebuildingImmediateInvocation || isImmediateFunctionContext())
17496 return E;
17498 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17499 /// It's OK if this fails; we'll also remove this in
17500 /// HandleImmediateInvocations, but catching it here allows us to avoid
17501 /// walking the AST looking for it in simple cases.
17502 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17503 if (auto *DeclRef =
17504 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17505 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17507 E = MaybeCreateExprWithCleanups(E);
17509 ConstantExpr *Res = ConstantExpr::Create(
17510 getASTContext(), E.get(),
17511 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17512 getASTContext()),
17513 /*IsImmediateInvocation*/ true);
17514 /// Value-dependent constant expressions should not be immediately
17515 /// evaluated until they are instantiated.
17516 if (!Res->isValueDependent())
17517 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17518 return Res;
17521 static void EvaluateAndDiagnoseImmediateInvocation(
17522 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
17523 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
17524 Expr::EvalResult Eval;
17525 Eval.Diag = &Notes;
17526 ConstantExpr *CE = Candidate.getPointer();
17527 bool Result = CE->EvaluateAsConstantExpr(
17528 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17529 if (!Result || !Notes.empty()) {
17530 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17531 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17532 InnerExpr = FunctionalCast->getSubExpr();
17533 FunctionDecl *FD = nullptr;
17534 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17535 FD = cast<FunctionDecl>(Call->getCalleeDecl());
17536 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17537 FD = Call->getConstructor();
17538 else
17539 llvm_unreachable("unhandled decl kind");
17540 assert(FD->isConsteval());
17541 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
17542 for (auto &Note : Notes)
17543 SemaRef.Diag(Note.first, Note.second);
17544 return;
17546 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
17549 static void RemoveNestedImmediateInvocation(
17550 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
17551 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
17552 struct ComplexRemove : TreeTransform<ComplexRemove> {
17553 using Base = TreeTransform<ComplexRemove>;
17554 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17555 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
17556 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
17557 CurrentII;
17558 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17559 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
17560 SmallVector<Sema::ImmediateInvocationCandidate,
17561 4>::reverse_iterator Current)
17562 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17563 void RemoveImmediateInvocation(ConstantExpr* E) {
17564 auto It = std::find_if(CurrentII, IISet.rend(),
17565 [E](Sema::ImmediateInvocationCandidate Elem) {
17566 return Elem.getPointer() == E;
17568 assert(It != IISet.rend() &&
17569 "ConstantExpr marked IsImmediateInvocation should "
17570 "be present");
17571 It->setInt(1); // Mark as deleted
17573 ExprResult TransformConstantExpr(ConstantExpr *E) {
17574 if (!E->isImmediateInvocation())
17575 return Base::TransformConstantExpr(E);
17576 RemoveImmediateInvocation(E);
17577 return Base::TransformExpr(E->getSubExpr());
17579 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17580 /// we need to remove its DeclRefExpr from the DRSet.
17581 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
17582 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
17583 return Base::TransformCXXOperatorCallExpr(E);
17585 /// Base::TransformInitializer skip ConstantExpr so we need to visit them
17586 /// here.
17587 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
17588 if (!Init)
17589 return Init;
17590 /// ConstantExpr are the first layer of implicit node to be removed so if
17591 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
17592 if (auto *CE = dyn_cast<ConstantExpr>(Init))
17593 if (CE->isImmediateInvocation())
17594 RemoveImmediateInvocation(CE);
17595 return Base::TransformInitializer(Init, NotCopyInit);
17597 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17598 DRSet.erase(E);
17599 return E;
17601 ExprResult TransformLambdaExpr(LambdaExpr *E) {
17602 // Do not rebuild lambdas to avoid creating a new type.
17603 // Lambdas have already been processed inside their eval context.
17604 return E;
17606 bool AlwaysRebuild() { return false; }
17607 bool ReplacingOriginal() { return true; }
17608 bool AllowSkippingCXXConstructExpr() {
17609 bool Res = AllowSkippingFirstCXXConstructExpr;
17610 AllowSkippingFirstCXXConstructExpr = true;
17611 return Res;
17613 bool AllowSkippingFirstCXXConstructExpr = true;
17614 } Transformer(SemaRef, Rec.ReferenceToConsteval,
17615 Rec.ImmediateInvocationCandidates, It);
17617 /// CXXConstructExpr with a single argument are getting skipped by
17618 /// TreeTransform in some situtation because they could be implicit. This
17619 /// can only occur for the top-level CXXConstructExpr because it is used
17620 /// nowhere in the expression being transformed therefore will not be rebuilt.
17621 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
17622 /// skipping the first CXXConstructExpr.
17623 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
17624 Transformer.AllowSkippingFirstCXXConstructExpr = false;
17626 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
17627 // The result may not be usable in case of previous compilation errors.
17628 // In this case evaluation of the expression may result in crash so just
17629 // don't do anything further with the result.
17630 if (Res.isUsable()) {
17631 Res = SemaRef.MaybeCreateExprWithCleanups(Res);
17632 It->getPointer()->setSubExpr(Res.get());
17636 static void
17637 HandleImmediateInvocations(Sema &SemaRef,
17638 Sema::ExpressionEvaluationContextRecord &Rec) {
17639 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
17640 Rec.ReferenceToConsteval.size() == 0) ||
17641 SemaRef.RebuildingImmediateInvocation)
17642 return;
17644 /// When we have more then 1 ImmediateInvocationCandidates we need to check
17645 /// for nested ImmediateInvocationCandidates. when we have only 1 we only
17646 /// need to remove ReferenceToConsteval in the immediate invocation.
17647 if (Rec.ImmediateInvocationCandidates.size() > 1) {
17649 /// Prevent sema calls during the tree transform from adding pointers that
17650 /// are already in the sets.
17651 llvm::SaveAndRestore<bool> DisableIITracking(
17652 SemaRef.RebuildingImmediateInvocation, true);
17654 /// Prevent diagnostic during tree transfrom as they are duplicates
17655 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
17657 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
17658 It != Rec.ImmediateInvocationCandidates.rend(); It++)
17659 if (!It->getInt())
17660 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
17661 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
17662 Rec.ReferenceToConsteval.size()) {
17663 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
17664 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17665 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
17666 bool VisitDeclRefExpr(DeclRefExpr *E) {
17667 DRSet.erase(E);
17668 return DRSet.size();
17670 } Visitor(Rec.ReferenceToConsteval);
17671 Visitor.TraverseStmt(
17672 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
17674 for (auto CE : Rec.ImmediateInvocationCandidates)
17675 if (!CE.getInt())
17676 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
17677 for (auto *DR : Rec.ReferenceToConsteval) {
17678 auto *FD = cast<FunctionDecl>(DR->getDecl());
17679 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
17680 << FD;
17681 SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
17685 void Sema::PopExpressionEvaluationContext() {
17686 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
17687 unsigned NumTypos = Rec.NumTypos;
17689 if (!Rec.Lambdas.empty()) {
17690 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
17691 if (!getLangOpts().CPlusPlus20 &&
17692 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
17693 Rec.isUnevaluated() ||
17694 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
17695 unsigned D;
17696 if (Rec.isUnevaluated()) {
17697 // C++11 [expr.prim.lambda]p2:
17698 // A lambda-expression shall not appear in an unevaluated operand
17699 // (Clause 5).
17700 D = diag::err_lambda_unevaluated_operand;
17701 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
17702 // C++1y [expr.const]p2:
17703 // A conditional-expression e is a core constant expression unless the
17704 // evaluation of e, following the rules of the abstract machine, would
17705 // evaluate [...] a lambda-expression.
17706 D = diag::err_lambda_in_constant_expression;
17707 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
17708 // C++17 [expr.prim.lamda]p2:
17709 // A lambda-expression shall not appear [...] in a template-argument.
17710 D = diag::err_lambda_in_invalid_context;
17711 } else
17712 llvm_unreachable("Couldn't infer lambda error message.");
17714 for (const auto *L : Rec.Lambdas)
17715 Diag(L->getBeginLoc(), D);
17719 WarnOnPendingNoDerefs(Rec);
17720 HandleImmediateInvocations(*this, Rec);
17722 // Warn on any volatile-qualified simple-assignments that are not discarded-
17723 // value expressions nor unevaluated operands (those cases get removed from
17724 // this list by CheckUnusedVolatileAssignment).
17725 for (auto *BO : Rec.VolatileAssignmentLHSs)
17726 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
17727 << BO->getType();
17729 // When are coming out of an unevaluated context, clear out any
17730 // temporaries that we may have created as part of the evaluation of
17731 // the expression in that context: they aren't relevant because they
17732 // will never be constructed.
17733 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
17734 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
17735 ExprCleanupObjects.end());
17736 Cleanup = Rec.ParentCleanup;
17737 CleanupVarDeclMarking();
17738 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
17739 // Otherwise, merge the contexts together.
17740 } else {
17741 Cleanup.mergeFrom(Rec.ParentCleanup);
17742 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
17743 Rec.SavedMaybeODRUseExprs.end());
17746 // Pop the current expression evaluation context off the stack.
17747 ExprEvalContexts.pop_back();
17749 // The global expression evaluation context record is never popped.
17750 ExprEvalContexts.back().NumTypos += NumTypos;
17753 void Sema::DiscardCleanupsInEvaluationContext() {
17754 ExprCleanupObjects.erase(
17755 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
17756 ExprCleanupObjects.end());
17757 Cleanup.reset();
17758 MaybeODRUseExprs.clear();
17761 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
17762 ExprResult Result = CheckPlaceholderExpr(E);
17763 if (Result.isInvalid())
17764 return ExprError();
17765 E = Result.get();
17766 if (!E->getType()->isVariablyModifiedType())
17767 return E;
17768 return TransformToPotentiallyEvaluated(E);
17771 /// Are we in a context that is potentially constant evaluated per C++20
17772 /// [expr.const]p12?
17773 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
17774 /// C++2a [expr.const]p12:
17775 // An expression or conversion is potentially constant evaluated if it is
17776 switch (SemaRef.ExprEvalContexts.back().Context) {
17777 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17778 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17780 // -- a manifestly constant-evaluated expression,
17781 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17782 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17783 case Sema::ExpressionEvaluationContext::DiscardedStatement:
17784 // -- a potentially-evaluated expression,
17785 case Sema::ExpressionEvaluationContext::UnevaluatedList:
17786 // -- an immediate subexpression of a braced-init-list,
17788 // -- [FIXME] an expression of the form & cast-expression that occurs
17789 // within a templated entity
17790 // -- a subexpression of one of the above that is not a subexpression of
17791 // a nested unevaluated operand.
17792 return true;
17794 case Sema::ExpressionEvaluationContext::Unevaluated:
17795 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17796 // Expressions in this context are never evaluated.
17797 return false;
17799 llvm_unreachable("Invalid context");
17802 /// Return true if this function has a calling convention that requires mangling
17803 /// in the size of the parameter pack.
17804 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
17805 // These manglings don't do anything on non-Windows or non-x86 platforms, so
17806 // we don't need parameter type sizes.
17807 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
17808 if (!TT.isOSWindows() || !TT.isX86())
17809 return false;
17811 // If this is C++ and this isn't an extern "C" function, parameters do not
17812 // need to be complete. In this case, C++ mangling will apply, which doesn't
17813 // use the size of the parameters.
17814 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
17815 return false;
17817 // Stdcall, fastcall, and vectorcall need this special treatment.
17818 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17819 switch (CC) {
17820 case CC_X86StdCall:
17821 case CC_X86FastCall:
17822 case CC_X86VectorCall:
17823 return true;
17824 default:
17825 break;
17827 return false;
17830 /// Require that all of the parameter types of function be complete. Normally,
17831 /// parameter types are only required to be complete when a function is called
17832 /// or defined, but to mangle functions with certain calling conventions, the
17833 /// mangler needs to know the size of the parameter list. In this situation,
17834 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
17835 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
17836 /// result in a linker error. Clang doesn't implement this behavior, and instead
17837 /// attempts to error at compile time.
17838 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
17839 SourceLocation Loc) {
17840 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
17841 FunctionDecl *FD;
17842 ParmVarDecl *Param;
17844 public:
17845 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
17846 : FD(FD), Param(Param) {}
17848 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17849 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17850 StringRef CCName;
17851 switch (CC) {
17852 case CC_X86StdCall:
17853 CCName = "stdcall";
17854 break;
17855 case CC_X86FastCall:
17856 CCName = "fastcall";
17857 break;
17858 case CC_X86VectorCall:
17859 CCName = "vectorcall";
17860 break;
17861 default:
17862 llvm_unreachable("CC does not need mangling");
17865 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
17866 << Param->getDeclName() << FD->getDeclName() << CCName;
17870 for (ParmVarDecl *Param : FD->parameters()) {
17871 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
17872 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
17876 namespace {
17877 enum class OdrUseContext {
17878 /// Declarations in this context are not odr-used.
17879 None,
17880 /// Declarations in this context are formally odr-used, but this is a
17881 /// dependent context.
17882 Dependent,
17883 /// Declarations in this context are odr-used but not actually used (yet).
17884 FormallyOdrUsed,
17885 /// Declarations in this context are used.
17886 Used
17890 /// Are we within a context in which references to resolved functions or to
17891 /// variables result in odr-use?
17892 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
17893 OdrUseContext Result;
17895 switch (SemaRef.ExprEvalContexts.back().Context) {
17896 case Sema::ExpressionEvaluationContext::Unevaluated:
17897 case Sema::ExpressionEvaluationContext::UnevaluatedList:
17898 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17899 return OdrUseContext::None;
17901 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17902 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17903 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17904 Result = OdrUseContext::Used;
17905 break;
17907 case Sema::ExpressionEvaluationContext::DiscardedStatement:
17908 Result = OdrUseContext::FormallyOdrUsed;
17909 break;
17911 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17912 // A default argument formally results in odr-use, but doesn't actually
17913 // result in a use in any real sense until it itself is used.
17914 Result = OdrUseContext::FormallyOdrUsed;
17915 break;
17918 if (SemaRef.CurContext->isDependentContext())
17919 return OdrUseContext::Dependent;
17921 return Result;
17924 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
17925 if (!Func->isConstexpr())
17926 return false;
17928 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
17929 return true;
17930 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
17931 return CCD && CCD->getInheritedConstructor();
17934 /// Mark a function referenced, and check whether it is odr-used
17935 /// (C++ [basic.def.odr]p2, C99 6.9p3)
17936 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
17937 bool MightBeOdrUse) {
17938 assert(Func && "No function?");
17940 Func->setReferenced();
17942 // Recursive functions aren't really used until they're used from some other
17943 // context.
17944 bool IsRecursiveCall = CurContext == Func;
17946 // C++11 [basic.def.odr]p3:
17947 // A function whose name appears as a potentially-evaluated expression is
17948 // odr-used if it is the unique lookup result or the selected member of a
17949 // set of overloaded functions [...].
17951 // We (incorrectly) mark overload resolution as an unevaluated context, so we
17952 // can just check that here.
17953 OdrUseContext OdrUse =
17954 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
17955 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
17956 OdrUse = OdrUseContext::FormallyOdrUsed;
17958 // Trivial default constructors and destructors are never actually used.
17959 // FIXME: What about other special members?
17960 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
17961 OdrUse == OdrUseContext::Used) {
17962 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
17963 if (Constructor->isDefaultConstructor())
17964 OdrUse = OdrUseContext::FormallyOdrUsed;
17965 if (isa<CXXDestructorDecl>(Func))
17966 OdrUse = OdrUseContext::FormallyOdrUsed;
17969 // C++20 [expr.const]p12:
17970 // A function [...] is needed for constant evaluation if it is [...] a
17971 // constexpr function that is named by an expression that is potentially
17972 // constant evaluated
17973 bool NeededForConstantEvaluation =
17974 isPotentiallyConstantEvaluatedContext(*this) &&
17975 isImplicitlyDefinableConstexprFunction(Func);
17977 // Determine whether we require a function definition to exist, per
17978 // C++11 [temp.inst]p3:
17979 // Unless a function template specialization has been explicitly
17980 // instantiated or explicitly specialized, the function template
17981 // specialization is implicitly instantiated when the specialization is
17982 // referenced in a context that requires a function definition to exist.
17983 // C++20 [temp.inst]p7:
17984 // The existence of a definition of a [...] function is considered to
17985 // affect the semantics of the program if the [...] function is needed for
17986 // constant evaluation by an expression
17987 // C++20 [basic.def.odr]p10:
17988 // Every program shall contain exactly one definition of every non-inline
17989 // function or variable that is odr-used in that program outside of a
17990 // discarded statement
17991 // C++20 [special]p1:
17992 // The implementation will implicitly define [defaulted special members]
17993 // if they are odr-used or needed for constant evaluation.
17995 // Note that we skip the implicit instantiation of templates that are only
17996 // used in unused default arguments or by recursive calls to themselves.
17997 // This is formally non-conforming, but seems reasonable in practice.
17998 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
17999 NeededForConstantEvaluation);
18001 // C++14 [temp.expl.spec]p6:
18002 // If a template [...] is explicitly specialized then that specialization
18003 // shall be declared before the first use of that specialization that would
18004 // cause an implicit instantiation to take place, in every translation unit
18005 // in which such a use occurs
18006 if (NeedDefinition &&
18007 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18008 Func->getMemberSpecializationInfo()))
18009 checkSpecializationReachability(Loc, Func);
18011 if (getLangOpts().CUDA)
18012 CheckCUDACall(Loc, Func);
18014 if (getLangOpts().SYCLIsDevice)
18015 checkSYCLDeviceFunction(Loc, Func);
18017 // If we need a definition, try to create one.
18018 if (NeedDefinition && !Func->getBody()) {
18019 runWithSufficientStackSpace(Loc, [&] {
18020 if (CXXConstructorDecl *Constructor =
18021 dyn_cast<CXXConstructorDecl>(Func)) {
18022 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
18023 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18024 if (Constructor->isDefaultConstructor()) {
18025 if (Constructor->isTrivial() &&
18026 !Constructor->hasAttr<DLLExportAttr>())
18027 return;
18028 DefineImplicitDefaultConstructor(Loc, Constructor);
18029 } else if (Constructor->isCopyConstructor()) {
18030 DefineImplicitCopyConstructor(Loc, Constructor);
18031 } else if (Constructor->isMoveConstructor()) {
18032 DefineImplicitMoveConstructor(Loc, Constructor);
18034 } else if (Constructor->getInheritedConstructor()) {
18035 DefineInheritingConstructor(Loc, Constructor);
18037 } else if (CXXDestructorDecl *Destructor =
18038 dyn_cast<CXXDestructorDecl>(Func)) {
18039 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
18040 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18041 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18042 return;
18043 DefineImplicitDestructor(Loc, Destructor);
18045 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18046 MarkVTableUsed(Loc, Destructor->getParent());
18047 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
18048 if (MethodDecl->isOverloadedOperator() &&
18049 MethodDecl->getOverloadedOperator() == OO_Equal) {
18050 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
18051 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18052 if (MethodDecl->isCopyAssignmentOperator())
18053 DefineImplicitCopyAssignment(Loc, MethodDecl);
18054 else if (MethodDecl->isMoveAssignmentOperator())
18055 DefineImplicitMoveAssignment(Loc, MethodDecl);
18057 } else if (isa<CXXConversionDecl>(MethodDecl) &&
18058 MethodDecl->getParent()->isLambda()) {
18059 CXXConversionDecl *Conversion =
18060 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
18061 if (Conversion->isLambdaToBlockPointerConversion())
18062 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
18063 else
18064 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
18065 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18066 MarkVTableUsed(Loc, MethodDecl->getParent());
18069 if (Func->isDefaulted() && !Func->isDeleted()) {
18070 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
18071 if (DCK != DefaultedComparisonKind::None)
18072 DefineDefaultedComparison(Loc, Func, DCK);
18075 // Implicit instantiation of function templates and member functions of
18076 // class templates.
18077 if (Func->isImplicitlyInstantiable()) {
18078 TemplateSpecializationKind TSK =
18079 Func->getTemplateSpecializationKindForInstantiation();
18080 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18081 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18082 if (FirstInstantiation) {
18083 PointOfInstantiation = Loc;
18084 if (auto *MSI = Func->getMemberSpecializationInfo())
18085 MSI->setPointOfInstantiation(Loc);
18086 // FIXME: Notify listener.
18087 else
18088 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18089 } else if (TSK != TSK_ImplicitInstantiation) {
18090 // Use the point of use as the point of instantiation, instead of the
18091 // point of explicit instantiation (which we track as the actual point
18092 // of instantiation). This gives better backtraces in diagnostics.
18093 PointOfInstantiation = Loc;
18096 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18097 Func->isConstexpr()) {
18098 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
18099 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
18100 CodeSynthesisContexts.size())
18101 PendingLocalImplicitInstantiations.push_back(
18102 std::make_pair(Func, PointOfInstantiation));
18103 else if (Func->isConstexpr())
18104 // Do not defer instantiations of constexpr functions, to avoid the
18105 // expression evaluator needing to call back into Sema if it sees a
18106 // call to such a function.
18107 InstantiateFunctionDefinition(PointOfInstantiation, Func);
18108 else {
18109 Func->setInstantiationIsPending(true);
18110 PendingInstantiations.push_back(
18111 std::make_pair(Func, PointOfInstantiation));
18112 // Notify the consumer that a function was implicitly instantiated.
18113 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
18116 } else {
18117 // Walk redefinitions, as some of them may be instantiable.
18118 for (auto *i : Func->redecls()) {
18119 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18120 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
18126 // C++14 [except.spec]p17:
18127 // An exception-specification is considered to be needed when:
18128 // - the function is odr-used or, if it appears in an unevaluated operand,
18129 // would be odr-used if the expression were potentially-evaluated;
18131 // Note, we do this even if MightBeOdrUse is false. That indicates that the
18132 // function is a pure virtual function we're calling, and in that case the
18133 // function was selected by overload resolution and we need to resolve its
18134 // exception specification for a different reason.
18135 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
18136 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
18137 ResolveExceptionSpec(Loc, FPT);
18139 // If this is the first "real" use, act on that.
18140 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18141 // Keep track of used but undefined functions.
18142 if (!Func->isDefined()) {
18143 if (mightHaveNonExternalLinkage(Func))
18144 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18145 else if (Func->getMostRecentDecl()->isInlined() &&
18146 !LangOpts.GNUInline &&
18147 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18148 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18149 else if (isExternalWithNoLinkageType(Func))
18150 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18153 // Some x86 Windows calling conventions mangle the size of the parameter
18154 // pack into the name. Computing the size of the parameters requires the
18155 // parameter types to be complete. Check that now.
18156 if (funcHasParameterSizeMangling(*this, Func))
18157 CheckCompleteParameterTypesForMangler(*this, Func, Loc);
18159 // In the MS C++ ABI, the compiler emits destructor variants where they are
18160 // used. If the destructor is used here but defined elsewhere, mark the
18161 // virtual base destructors referenced. If those virtual base destructors
18162 // are inline, this will ensure they are defined when emitting the complete
18163 // destructor variant. This checking may be redundant if the destructor is
18164 // provided later in this TU.
18165 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
18166 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18167 CXXRecordDecl *Parent = Dtor->getParent();
18168 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18169 CheckCompleteDestructorVariant(Loc, Dtor);
18173 Func->markUsed(Context);
18177 /// Directly mark a variable odr-used. Given a choice, prefer to use
18178 /// MarkVariableReferenced since it does additional checks and then
18179 /// calls MarkVarDeclODRUsed.
18180 /// If the variable must be captured:
18181 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18182 /// - else capture it in the DeclContext that maps to the
18183 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18184 static void
18185 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
18186 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18187 // Keep track of used but undefined variables.
18188 // FIXME: We shouldn't suppress this warning for static data members.
18189 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
18190 (!Var->isExternallyVisible() || Var->isInline() ||
18191 SemaRef.isExternalWithNoLinkageType(Var)) &&
18192 !(Var->isStaticDataMember() && Var->hasInit())) {
18193 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
18194 if (old.isInvalid())
18195 old = Loc;
18197 QualType CaptureType, DeclRefType;
18198 if (SemaRef.LangOpts.OpenMP)
18199 SemaRef.tryCaptureOpenMPLambdas(Var);
18200 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
18201 /*EllipsisLoc*/ SourceLocation(),
18202 /*BuildAndDiagnose*/ true,
18203 CaptureType, DeclRefType,
18204 FunctionScopeIndexToStopAt);
18206 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18207 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18208 auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
18209 auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
18210 if (VarTarget == Sema::CVT_Host &&
18211 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
18212 UserTarget == Sema::CFT_Global)) {
18213 // Diagnose ODR-use of host global variables in device functions.
18214 // Reference of device global variables in host functions is allowed
18215 // through shadow variables therefore it is not diagnosed.
18216 if (SemaRef.LangOpts.CUDAIsDevice) {
18217 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18218 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
18219 SemaRef.targetDiag(Var->getLocation(),
18220 Var->getType().isConstQualified()
18221 ? diag::note_cuda_const_var_unpromoted
18222 : diag::note_cuda_host_var);
18224 } else if (VarTarget == Sema::CVT_Device &&
18225 (UserTarget == Sema::CFT_Host ||
18226 UserTarget == Sema::CFT_HostDevice)) {
18227 // Record a CUDA/HIP device side variable if it is ODR-used
18228 // by host code. This is done conservatively, when the variable is
18229 // referenced in any of the following contexts:
18230 // - a non-function context
18231 // - a host function
18232 // - a host device function
18233 // This makes the ODR-use of the device side variable by host code to
18234 // be visible in the device compilation for the compiler to be able to
18235 // emit template variables instantiated by host code only and to
18236 // externalize the static device side variable ODR-used by host code.
18237 if (!Var->hasExternalStorage())
18238 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
18239 else if (SemaRef.LangOpts.GPURelocatableDeviceCode)
18240 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var);
18244 Var->markUsed(SemaRef.Context);
18247 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
18248 SourceLocation Loc,
18249 unsigned CapturingScopeIndex) {
18250 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18253 void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc,
18254 ValueDecl *var) {
18255 DeclContext *VarDC = var->getDeclContext();
18257 // If the parameter still belongs to the translation unit, then
18258 // we're actually just using one parameter in the declaration of
18259 // the next.
18260 if (isa<ParmVarDecl>(var) &&
18261 isa<TranslationUnitDecl>(VarDC))
18262 return;
18264 // For C code, don't diagnose about capture if we're not actually in code
18265 // right now; it's impossible to write a non-constant expression outside of
18266 // function context, so we'll get other (more useful) diagnostics later.
18268 // For C++, things get a bit more nasty... it would be nice to suppress this
18269 // diagnostic for certain cases like using a local variable in an array bound
18270 // for a member of a local class, but the correct predicate is not obvious.
18271 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18272 return;
18274 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18275 unsigned ContextKind = 3; // unknown
18276 if (isa<CXXMethodDecl>(VarDC) &&
18277 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18278 ContextKind = 2;
18279 } else if (isa<FunctionDecl>(VarDC)) {
18280 ContextKind = 0;
18281 } else if (isa<BlockDecl>(VarDC)) {
18282 ContextKind = 1;
18285 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18286 << var << ValueKind << ContextKind << VarDC;
18287 S.Diag(var->getLocation(), diag::note_entity_declared_at)
18288 << var;
18290 // FIXME: Add additional diagnostic info about class etc. which prevents
18291 // capture.
18294 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,
18295 ValueDecl *Var,
18296 bool &SubCapturesAreNested,
18297 QualType &CaptureType,
18298 QualType &DeclRefType) {
18299 // Check whether we've already captured it.
18300 if (CSI->CaptureMap.count(Var)) {
18301 // If we found a capture, any subcaptures are nested.
18302 SubCapturesAreNested = true;
18304 // Retrieve the capture type for this variable.
18305 CaptureType = CSI->getCapture(Var).getCaptureType();
18307 // Compute the type of an expression that refers to this variable.
18308 DeclRefType = CaptureType.getNonReferenceType();
18310 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18311 // are mutable in the sense that user can change their value - they are
18312 // private instances of the captured declarations.
18313 const Capture &Cap = CSI->getCapture(Var);
18314 if (Cap.isCopyCapture() &&
18315 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
18316 !(isa<CapturedRegionScopeInfo>(CSI) &&
18317 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18318 DeclRefType.addConst();
18319 return true;
18321 return false;
18324 // Only block literals, captured statements, and lambda expressions can
18325 // capture; other scopes don't work.
18326 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC,
18327 ValueDecl *Var,
18328 SourceLocation Loc,
18329 const bool Diagnose,
18330 Sema &S) {
18331 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
18332 return getLambdaAwareParentOfDeclContext(DC);
18334 ValueDecl *Underlying = Var;
18335 auto *BD = dyn_cast_or_null<BindingDecl>(Var);
18336 if (BD)
18337 Underlying = BD->getDecomposedDecl();
18339 if (auto *VD = dyn_cast<VarDecl>(Underlying)) {
18340 if (VD->hasLocalStorage() && Diagnose)
18341 diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var);
18343 return nullptr;
18346 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18347 // certain types of variables (unnamed, variably modified types etc.)
18348 // so check for eligibility.
18349 static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var,
18350 SourceLocation Loc, const bool Diagnose,
18351 Sema &S) {
18353 assert((isa<VarDecl, BindingDecl>(Var)) &&
18354 "Only variables and structured bindings can be captured");
18356 bool IsBlock = isa<BlockScopeInfo>(CSI);
18357 bool IsLambda = isa<LambdaScopeInfo>(CSI);
18359 // Lambdas are not allowed to capture unnamed variables
18360 // (e.g. anonymous unions).
18361 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18362 // assuming that's the intent.
18363 if (IsLambda && !Var->getDeclName()) {
18364 if (Diagnose) {
18365 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18366 S.Diag(Var->getLocation(), diag::note_declared_at);
18368 return false;
18371 // Prohibit variably-modified types in blocks; they're difficult to deal with.
18372 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18373 if (Diagnose) {
18374 S.Diag(Loc, diag::err_ref_vm_type);
18375 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18377 return false;
18379 // Prohibit structs with flexible array members too.
18380 // We cannot capture what is in the tail end of the struct.
18381 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
18382 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
18383 if (Diagnose) {
18384 if (IsBlock)
18385 S.Diag(Loc, diag::err_ref_flexarray_type);
18386 else
18387 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18388 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18390 return false;
18393 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18394 // Lambdas and captured statements are not allowed to capture __block
18395 // variables; they don't support the expected semantics.
18396 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18397 if (Diagnose) {
18398 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18399 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18401 return false;
18403 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18404 if (S.getLangOpts().OpenCL && IsBlock &&
18405 Var->getType()->isBlockPointerType()) {
18406 if (Diagnose)
18407 S.Diag(Loc, diag::err_opencl_block_ref_block);
18408 return false;
18411 if (isa<BindingDecl>(Var)) {
18412 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
18413 if (Diagnose)
18414 diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var);
18415 return false;
18416 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
18417 S.Diag(Loc, S.LangOpts.CPlusPlus20
18418 ? diag::warn_cxx17_compat_capture_binding
18419 : diag::ext_capture_binding)
18420 << Var;
18421 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18425 return true;
18428 // Returns true if the capture by block was successful.
18429 static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,
18430 SourceLocation Loc, const bool BuildAndDiagnose,
18431 QualType &CaptureType, QualType &DeclRefType,
18432 const bool Nested, Sema &S, bool Invalid) {
18433 bool ByRef = false;
18435 // Blocks are not allowed to capture arrays, excepting OpenCL.
18436 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18437 // (decayed to pointers).
18438 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18439 if (BuildAndDiagnose) {
18440 S.Diag(Loc, diag::err_ref_array_type);
18441 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18442 Invalid = true;
18443 } else {
18444 return false;
18448 // Forbid the block-capture of autoreleasing variables.
18449 if (!Invalid &&
18450 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
18451 if (BuildAndDiagnose) {
18452 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
18453 << /*block*/ 0;
18454 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18455 Invalid = true;
18456 } else {
18457 return false;
18461 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18462 if (const auto *PT = CaptureType->getAs<PointerType>()) {
18463 QualType PointeeTy = PT->getPointeeType();
18465 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
18466 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
18467 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
18468 if (BuildAndDiagnose) {
18469 SourceLocation VarLoc = Var->getLocation();
18470 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
18471 S.Diag(VarLoc, diag::note_declare_parameter_strong);
18476 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18477 if (HasBlocksAttr || CaptureType->isReferenceType() ||
18478 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
18479 // Block capture by reference does not change the capture or
18480 // declaration reference types.
18481 ByRef = true;
18482 } else {
18483 // Block capture by copy introduces 'const'.
18484 CaptureType = CaptureType.getNonReferenceType().withConst();
18485 DeclRefType = CaptureType;
18488 // Actually capture the variable.
18489 if (BuildAndDiagnose)
18490 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
18491 CaptureType, Invalid);
18493 return !Invalid;
18496 /// Capture the given variable in the captured region.
18497 static bool captureInCapturedRegion(
18498 CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc,
18499 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
18500 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
18501 bool IsTopScope, Sema &S, bool Invalid) {
18502 // By default, capture variables by reference.
18503 bool ByRef = true;
18504 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18505 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18506 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
18507 // Using an LValue reference type is consistent with Lambdas (see below).
18508 if (S.isOpenMPCapturedDecl(Var)) {
18509 bool HasConst = DeclRefType.isConstQualified();
18510 DeclRefType = DeclRefType.getUnqualifiedType();
18511 // Don't lose diagnostics about assignments to const.
18512 if (HasConst)
18513 DeclRefType.addConst();
18515 // Do not capture firstprivates in tasks.
18516 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
18517 OMPC_unknown)
18518 return true;
18519 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
18520 RSI->OpenMPCaptureLevel);
18523 if (ByRef)
18524 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18525 else
18526 CaptureType = DeclRefType;
18528 // Actually capture the variable.
18529 if (BuildAndDiagnose)
18530 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
18531 Loc, SourceLocation(), CaptureType, Invalid);
18533 return !Invalid;
18536 /// Capture the given variable in the lambda.
18537 static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var,
18538 SourceLocation Loc, const bool BuildAndDiagnose,
18539 QualType &CaptureType, QualType &DeclRefType,
18540 const bool RefersToCapturedVariable,
18541 const Sema::TryCaptureKind Kind,
18542 SourceLocation EllipsisLoc, const bool IsTopScope,
18543 Sema &S, bool Invalid) {
18544 // Determine whether we are capturing by reference or by value.
18545 bool ByRef = false;
18546 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18547 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18548 } else {
18549 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
18552 BindingDecl *BD = dyn_cast<BindingDecl>(Var);
18553 // FIXME: We should support capturing structured bindings in OpenMP.
18554 if (!Invalid && BD && S.LangOpts.OpenMP) {
18555 if (BuildAndDiagnose) {
18556 S.Diag(Loc, diag::err_capture_binding_openmp) << Var;
18557 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18559 Invalid = true;
18562 // Compute the type of the field that will capture this variable.
18563 if (ByRef) {
18564 // C++11 [expr.prim.lambda]p15:
18565 // An entity is captured by reference if it is implicitly or
18566 // explicitly captured but not captured by copy. It is
18567 // unspecified whether additional unnamed non-static data
18568 // members are declared in the closure type for entities
18569 // captured by reference.
18571 // FIXME: It is not clear whether we want to build an lvalue reference
18572 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
18573 // to do the former, while EDG does the latter. Core issue 1249 will
18574 // clarify, but for now we follow GCC because it's a more permissive and
18575 // easily defensible position.
18576 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18577 } else {
18578 // C++11 [expr.prim.lambda]p14:
18579 // For each entity captured by copy, an unnamed non-static
18580 // data member is declared in the closure type. The
18581 // declaration order of these members is unspecified. The type
18582 // of such a data member is the type of the corresponding
18583 // captured entity if the entity is not a reference to an
18584 // object, or the referenced type otherwise. [Note: If the
18585 // captured entity is a reference to a function, the
18586 // corresponding data member is also a reference to a
18587 // function. - end note ]
18588 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
18589 if (!RefType->getPointeeType()->isFunctionType())
18590 CaptureType = RefType->getPointeeType();
18593 // Forbid the lambda copy-capture of autoreleasing variables.
18594 if (!Invalid &&
18595 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
18596 if (BuildAndDiagnose) {
18597 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
18598 S.Diag(Var->getLocation(), diag::note_previous_decl)
18599 << Var->getDeclName();
18600 Invalid = true;
18601 } else {
18602 return false;
18606 // Make sure that by-copy captures are of a complete and non-abstract type.
18607 if (!Invalid && BuildAndDiagnose) {
18608 if (!CaptureType->isDependentType() &&
18609 S.RequireCompleteSizedType(
18610 Loc, CaptureType,
18611 diag::err_capture_of_incomplete_or_sizeless_type,
18612 Var->getDeclName()))
18613 Invalid = true;
18614 else if (S.RequireNonAbstractType(Loc, CaptureType,
18615 diag::err_capture_of_abstract_type))
18616 Invalid = true;
18620 // Compute the type of a reference to this captured variable.
18621 if (ByRef)
18622 DeclRefType = CaptureType.getNonReferenceType();
18623 else {
18624 // C++ [expr.prim.lambda]p5:
18625 // The closure type for a lambda-expression has a public inline
18626 // function call operator [...]. This function call operator is
18627 // declared const (9.3.1) if and only if the lambda-expression's
18628 // parameter-declaration-clause is not followed by mutable.
18629 DeclRefType = CaptureType.getNonReferenceType();
18630 if (!LSI->Mutable && !CaptureType->isReferenceType())
18631 DeclRefType.addConst();
18634 // Add the capture.
18635 if (BuildAndDiagnose)
18636 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
18637 Loc, EllipsisLoc, CaptureType, Invalid);
18639 return !Invalid;
18642 static bool canCaptureVariableByCopy(ValueDecl *Var,
18643 const ASTContext &Context) {
18644 // Offer a Copy fix even if the type is dependent.
18645 if (Var->getType()->isDependentType())
18646 return true;
18647 QualType T = Var->getType().getNonReferenceType();
18648 if (T.isTriviallyCopyableType(Context))
18649 return true;
18650 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
18652 if (!(RD = RD->getDefinition()))
18653 return false;
18654 if (RD->hasSimpleCopyConstructor())
18655 return true;
18656 if (RD->hasUserDeclaredCopyConstructor())
18657 for (CXXConstructorDecl *Ctor : RD->ctors())
18658 if (Ctor->isCopyConstructor())
18659 return !Ctor->isDeleted();
18661 return false;
18664 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or
18665 /// default capture. Fixes may be omitted if they aren't allowed by the
18666 /// standard, for example we can't emit a default copy capture fix-it if we
18667 /// already explicitly copy capture capture another variable.
18668 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
18669 ValueDecl *Var) {
18670 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
18671 // Don't offer Capture by copy of default capture by copy fixes if Var is
18672 // known not to be copy constructible.
18673 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
18675 SmallString<32> FixBuffer;
18676 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
18677 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
18678 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
18679 if (ShouldOfferCopyFix) {
18680 // Offer fixes to insert an explicit capture for the variable.
18681 // [] -> [VarName]
18682 // [OtherCapture] -> [OtherCapture, VarName]
18683 FixBuffer.assign({Separator, Var->getName()});
18684 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18685 << Var << /*value*/ 0
18686 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18688 // As above but capture by reference.
18689 FixBuffer.assign({Separator, "&", Var->getName()});
18690 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18691 << Var << /*reference*/ 1
18692 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18695 // Only try to offer default capture if there are no captures excluding this
18696 // and init captures.
18697 // [this]: OK.
18698 // [X = Y]: OK.
18699 // [&A, &B]: Don't offer.
18700 // [A, B]: Don't offer.
18701 if (llvm::any_of(LSI->Captures, [](Capture &C) {
18702 return !C.isThisCapture() && !C.isInitCapture();
18704 return;
18706 // The default capture specifiers, '=' or '&', must appear first in the
18707 // capture body.
18708 SourceLocation DefaultInsertLoc =
18709 LSI->IntroducerRange.getBegin().getLocWithOffset(1);
18711 if (ShouldOfferCopyFix) {
18712 bool CanDefaultCopyCapture = true;
18713 // [=, *this] OK since c++17
18714 // [=, this] OK since c++20
18715 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
18716 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
18717 ? LSI->getCXXThisCapture().isCopyCapture()
18718 : false;
18719 // We can't use default capture by copy if any captures already specified
18720 // capture by copy.
18721 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
18722 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
18723 })) {
18724 FixBuffer.assign({"=", Separator});
18725 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18726 << /*value*/ 0
18727 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18731 // We can't use default capture by reference if any captures already specified
18732 // capture by reference.
18733 if (llvm::none_of(LSI->Captures, [](Capture &C) {
18734 return !C.isInitCapture() && C.isReferenceCapture() &&
18735 !C.isThisCapture();
18736 })) {
18737 FixBuffer.assign({"&", Separator});
18738 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18739 << /*reference*/ 1
18740 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18744 bool Sema::tryCaptureVariable(
18745 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
18746 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
18747 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
18748 // An init-capture is notionally from the context surrounding its
18749 // declaration, but its parent DC is the lambda class.
18750 DeclContext *VarDC = Var->getDeclContext();
18751 const auto *VD = dyn_cast<VarDecl>(Var);
18752 if (VD) {
18753 if (VD->isInitCapture())
18754 VarDC = VarDC->getParent();
18755 } else {
18756 VD = dyn_cast<DecompositionDecl>(
18757 cast<BindingDecl>(Var)->getDecomposedDecl());
18759 assert(VD && "Cannot capture a null variable");
18761 DeclContext *DC = CurContext;
18762 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
18763 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
18764 // We need to sync up the Declaration Context with the
18765 // FunctionScopeIndexToStopAt
18766 if (FunctionScopeIndexToStopAt) {
18767 unsigned FSIndex = FunctionScopes.size() - 1;
18768 while (FSIndex != MaxFunctionScopesIndex) {
18769 DC = getLambdaAwareParentOfDeclContext(DC);
18770 --FSIndex;
18775 // If the variable is declared in the current context, there is no need to
18776 // capture it.
18777 if (VarDC == DC) return true;
18779 // Capture global variables if it is required to use private copy of this
18780 // variable.
18781 bool IsGlobal = !VD->hasLocalStorage();
18782 if (IsGlobal &&
18783 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
18784 MaxFunctionScopesIndex)))
18785 return true;
18787 if (isa<VarDecl>(Var))
18788 Var = cast<VarDecl>(Var->getCanonicalDecl());
18790 // Walk up the stack to determine whether we can capture the variable,
18791 // performing the "simple" checks that don't depend on type. We stop when
18792 // we've either hit the declared scope of the variable or find an existing
18793 // capture of that variable. We start from the innermost capturing-entity
18794 // (the DC) and ensure that all intervening capturing-entities
18795 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
18796 // declcontext can either capture the variable or have already captured
18797 // the variable.
18798 CaptureType = Var->getType();
18799 DeclRefType = CaptureType.getNonReferenceType();
18800 bool Nested = false;
18801 bool Explicit = (Kind != TryCapture_Implicit);
18802 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
18803 do {
18804 // Only block literals, captured statements, and lambda expressions can
18805 // capture; other scopes don't work.
18806 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
18807 ExprLoc,
18808 BuildAndDiagnose,
18809 *this);
18810 // We need to check for the parent *first* because, if we *have*
18811 // private-captured a global variable, we need to recursively capture it in
18812 // intermediate blocks, lambdas, etc.
18813 if (!ParentDC) {
18814 if (IsGlobal) {
18815 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
18816 break;
18818 return true;
18821 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
18822 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
18825 // Check whether we've already captured it.
18826 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
18827 DeclRefType)) {
18828 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
18829 break;
18831 // If we are instantiating a generic lambda call operator body,
18832 // we do not want to capture new variables. What was captured
18833 // during either a lambdas transformation or initial parsing
18834 // should be used.
18835 if (isGenericLambdaCallOperatorSpecialization(DC)) {
18836 if (BuildAndDiagnose) {
18837 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18838 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
18839 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18840 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18841 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18842 buildLambdaCaptureFixit(*this, LSI, Var);
18843 } else
18844 diagnoseUncapturableValueReferenceOrBinding(*this, ExprLoc, Var);
18846 return true;
18849 // Try to capture variable-length arrays types.
18850 if (Var->getType()->isVariablyModifiedType()) {
18851 // We're going to walk down into the type and look for VLA
18852 // expressions.
18853 QualType QTy = Var->getType();
18854 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18855 QTy = PVD->getOriginalType();
18856 captureVariablyModifiedType(Context, QTy, CSI);
18859 if (getLangOpts().OpenMP) {
18860 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18861 // OpenMP private variables should not be captured in outer scope, so
18862 // just break here. Similarly, global variables that are captured in a
18863 // target region should not be captured outside the scope of the region.
18864 if (RSI->CapRegionKind == CR_OpenMP) {
18865 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
18866 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
18867 // If the variable is private (i.e. not captured) and has variably
18868 // modified type, we still need to capture the type for correct
18869 // codegen in all regions, associated with the construct. Currently,
18870 // it is captured in the innermost captured region only.
18871 if (IsOpenMPPrivateDecl != OMPC_unknown &&
18872 Var->getType()->isVariablyModifiedType()) {
18873 QualType QTy = Var->getType();
18874 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18875 QTy = PVD->getOriginalType();
18876 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
18877 I < E; ++I) {
18878 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
18879 FunctionScopes[FunctionScopesIndex - I]);
18880 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
18881 "Wrong number of captured regions associated with the "
18882 "OpenMP construct.");
18883 captureVariablyModifiedType(Context, QTy, OuterRSI);
18886 bool IsTargetCap =
18887 IsOpenMPPrivateDecl != OMPC_private &&
18888 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
18889 RSI->OpenMPCaptureLevel);
18890 // Do not capture global if it is not privatized in outer regions.
18891 bool IsGlobalCap =
18892 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
18893 RSI->OpenMPCaptureLevel);
18895 // When we detect target captures we are looking from inside the
18896 // target region, therefore we need to propagate the capture from the
18897 // enclosing region. Therefore, the capture is not initially nested.
18898 if (IsTargetCap)
18899 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
18901 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
18902 (IsGlobal && !IsGlobalCap)) {
18903 Nested = !IsTargetCap;
18904 bool HasConst = DeclRefType.isConstQualified();
18905 DeclRefType = DeclRefType.getUnqualifiedType();
18906 // Don't lose diagnostics about assignments to const.
18907 if (HasConst)
18908 DeclRefType.addConst();
18909 CaptureType = Context.getLValueReferenceType(DeclRefType);
18910 break;
18915 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
18916 // No capture-default, and this is not an explicit capture
18917 // so cannot capture this variable.
18918 if (BuildAndDiagnose) {
18919 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18920 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18921 auto *LSI = cast<LambdaScopeInfo>(CSI);
18922 if (LSI->Lambda) {
18923 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18924 buildLambdaCaptureFixit(*this, LSI, Var);
18926 // FIXME: If we error out because an outer lambda can not implicitly
18927 // capture a variable that an inner lambda explicitly captures, we
18928 // should have the inner lambda do the explicit capture - because
18929 // it makes for cleaner diagnostics later. This would purely be done
18930 // so that the diagnostic does not misleadingly claim that a variable
18931 // can not be captured by a lambda implicitly even though it is captured
18932 // explicitly. Suggestion:
18933 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
18934 // at the function head
18935 // - cache the StartingDeclContext - this must be a lambda
18936 // - captureInLambda in the innermost lambda the variable.
18938 return true;
18941 FunctionScopesIndex--;
18942 DC = ParentDC;
18943 Explicit = false;
18944 } while (!VarDC->Equals(DC));
18946 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
18947 // computing the type of the capture at each step, checking type-specific
18948 // requirements, and adding captures if requested.
18949 // If the variable had already been captured previously, we start capturing
18950 // at the lambda nested within that one.
18951 bool Invalid = false;
18952 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
18953 ++I) {
18954 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
18956 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18957 // certain types of variables (unnamed, variably modified types etc.)
18958 // so check for eligibility.
18959 if (!Invalid)
18960 Invalid =
18961 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
18963 // After encountering an error, if we're actually supposed to capture, keep
18964 // capturing in nested contexts to suppress any follow-on diagnostics.
18965 if (Invalid && !BuildAndDiagnose)
18966 return true;
18968 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
18969 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18970 DeclRefType, Nested, *this, Invalid);
18971 Nested = true;
18972 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18973 Invalid = !captureInCapturedRegion(
18974 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
18975 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
18976 Nested = true;
18977 } else {
18978 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18979 Invalid =
18980 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18981 DeclRefType, Nested, Kind, EllipsisLoc,
18982 /*IsTopScope*/ I == N - 1, *this, Invalid);
18983 Nested = true;
18986 if (Invalid && !BuildAndDiagnose)
18987 return true;
18989 return Invalid;
18992 bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
18993 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
18994 QualType CaptureType;
18995 QualType DeclRefType;
18996 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
18997 /*BuildAndDiagnose=*/true, CaptureType,
18998 DeclRefType, nullptr);
19001 bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) {
19002 QualType CaptureType;
19003 QualType DeclRefType;
19004 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
19005 /*BuildAndDiagnose=*/false, CaptureType,
19006 DeclRefType, nullptr);
19009 QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) {
19010 QualType CaptureType;
19011 QualType DeclRefType;
19013 // Determine whether we can capture this variable.
19014 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
19015 /*BuildAndDiagnose=*/false, CaptureType,
19016 DeclRefType, nullptr))
19017 return QualType();
19019 return DeclRefType;
19022 namespace {
19023 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19024 // The produced TemplateArgumentListInfo* points to data stored within this
19025 // object, so should only be used in contexts where the pointer will not be
19026 // used after the CopiedTemplateArgs object is destroyed.
19027 class CopiedTemplateArgs {
19028 bool HasArgs;
19029 TemplateArgumentListInfo TemplateArgStorage;
19030 public:
19031 template<typename RefExpr>
19032 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
19033 if (HasArgs)
19034 E->copyTemplateArgumentsInto(TemplateArgStorage);
19036 operator TemplateArgumentListInfo*()
19037 #ifdef __has_cpp_attribute
19038 #if __has_cpp_attribute(clang::lifetimebound)
19039 [[clang::lifetimebound]]
19040 #endif
19041 #endif
19043 return HasArgs ? &TemplateArgStorage : nullptr;
19048 /// Walk the set of potential results of an expression and mark them all as
19049 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19051 /// \return A new expression if we found any potential results, ExprEmpty() if
19052 /// not, and ExprError() if we diagnosed an error.
19053 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
19054 NonOdrUseReason NOUR) {
19055 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19056 // an object that satisfies the requirements for appearing in a
19057 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19058 // is immediately applied." This function handles the lvalue-to-rvalue
19059 // conversion part.
19061 // If we encounter a node that claims to be an odr-use but shouldn't be, we
19062 // transform it into the relevant kind of non-odr-use node and rebuild the
19063 // tree of nodes leading to it.
19065 // This is a mini-TreeTransform that only transforms a restricted subset of
19066 // nodes (and only certain operands of them).
19068 // Rebuild a subexpression.
19069 auto Rebuild = [&](Expr *Sub) {
19070 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
19073 // Check whether a potential result satisfies the requirements of NOUR.
19074 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
19075 // Any entity other than a VarDecl is always odr-used whenever it's named
19076 // in a potentially-evaluated expression.
19077 auto *VD = dyn_cast<VarDecl>(D);
19078 if (!VD)
19079 return true;
19081 // C++2a [basic.def.odr]p4:
19082 // A variable x whose name appears as a potentially-evalauted expression
19083 // e is odr-used by e unless
19084 // -- x is a reference that is usable in constant expressions, or
19085 // -- x is a variable of non-reference type that is usable in constant
19086 // expressions and has no mutable subobjects, and e is an element of
19087 // the set of potential results of an expression of
19088 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19089 // conversion is applied, or
19090 // -- x is a variable of non-reference type, and e is an element of the
19091 // set of potential results of a discarded-value expression to which
19092 // the lvalue-to-rvalue conversion is not applied
19094 // We check the first bullet and the "potentially-evaluated" condition in
19095 // BuildDeclRefExpr. We check the type requirements in the second bullet
19096 // in CheckLValueToRValueConversionOperand below.
19097 switch (NOUR) {
19098 case NOUR_None:
19099 case NOUR_Unevaluated:
19100 llvm_unreachable("unexpected non-odr-use-reason");
19102 case NOUR_Constant:
19103 // Constant references were handled when they were built.
19104 if (VD->getType()->isReferenceType())
19105 return true;
19106 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
19107 if (RD->hasMutableFields())
19108 return true;
19109 if (!VD->isUsableInConstantExpressions(S.Context))
19110 return true;
19111 break;
19113 case NOUR_Discarded:
19114 if (VD->getType()->isReferenceType())
19115 return true;
19116 break;
19118 return false;
19121 // Mark that this expression does not constitute an odr-use.
19122 auto MarkNotOdrUsed = [&] {
19123 S.MaybeODRUseExprs.remove(E);
19124 if (LambdaScopeInfo *LSI = S.getCurLambda())
19125 LSI->markVariableExprAsNonODRUsed(E);
19128 // C++2a [basic.def.odr]p2:
19129 // The set of potential results of an expression e is defined as follows:
19130 switch (E->getStmtClass()) {
19131 // -- If e is an id-expression, ...
19132 case Expr::DeclRefExprClass: {
19133 auto *DRE = cast<DeclRefExpr>(E);
19134 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19135 break;
19137 // Rebuild as a non-odr-use DeclRefExpr.
19138 MarkNotOdrUsed();
19139 return DeclRefExpr::Create(
19140 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19141 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19142 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19143 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19146 case Expr::FunctionParmPackExprClass: {
19147 auto *FPPE = cast<FunctionParmPackExpr>(E);
19148 // If any of the declarations in the pack is odr-used, then the expression
19149 // as a whole constitutes an odr-use.
19150 for (VarDecl *D : *FPPE)
19151 if (IsPotentialResultOdrUsed(D))
19152 return ExprEmpty();
19154 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19155 // nothing cares about whether we marked this as an odr-use, but it might
19156 // be useful for non-compiler tools.
19157 MarkNotOdrUsed();
19158 break;
19161 // -- If e is a subscripting operation with an array operand...
19162 case Expr::ArraySubscriptExprClass: {
19163 auto *ASE = cast<ArraySubscriptExpr>(E);
19164 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19165 if (!OldBase->getType()->isArrayType())
19166 break;
19167 ExprResult Base = Rebuild(OldBase);
19168 if (!Base.isUsable())
19169 return Base;
19170 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19171 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19172 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19173 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19174 ASE->getRBracketLoc());
19177 case Expr::MemberExprClass: {
19178 auto *ME = cast<MemberExpr>(E);
19179 // -- If e is a class member access expression [...] naming a non-static
19180 // data member...
19181 if (isa<FieldDecl>(ME->getMemberDecl())) {
19182 ExprResult Base = Rebuild(ME->getBase());
19183 if (!Base.isUsable())
19184 return Base;
19185 return MemberExpr::Create(
19186 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19187 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19188 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19189 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19190 ME->getObjectKind(), ME->isNonOdrUse());
19193 if (ME->getMemberDecl()->isCXXInstanceMember())
19194 break;
19196 // -- If e is a class member access expression naming a static data member,
19197 // ...
19198 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19199 break;
19201 // Rebuild as a non-odr-use MemberExpr.
19202 MarkNotOdrUsed();
19203 return MemberExpr::Create(
19204 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19205 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19206 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19207 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19210 case Expr::BinaryOperatorClass: {
19211 auto *BO = cast<BinaryOperator>(E);
19212 Expr *LHS = BO->getLHS();
19213 Expr *RHS = BO->getRHS();
19214 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19215 if (BO->getOpcode() == BO_PtrMemD) {
19216 ExprResult Sub = Rebuild(LHS);
19217 if (!Sub.isUsable())
19218 return Sub;
19219 LHS = Sub.get();
19220 // -- If e is a comma expression, ...
19221 } else if (BO->getOpcode() == BO_Comma) {
19222 ExprResult Sub = Rebuild(RHS);
19223 if (!Sub.isUsable())
19224 return Sub;
19225 RHS = Sub.get();
19226 } else {
19227 break;
19229 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
19230 LHS, RHS);
19233 // -- If e has the form (e1)...
19234 case Expr::ParenExprClass: {
19235 auto *PE = cast<ParenExpr>(E);
19236 ExprResult Sub = Rebuild(PE->getSubExpr());
19237 if (!Sub.isUsable())
19238 return Sub;
19239 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
19242 // -- If e is a glvalue conditional expression, ...
19243 // We don't apply this to a binary conditional operator. FIXME: Should we?
19244 case Expr::ConditionalOperatorClass: {
19245 auto *CO = cast<ConditionalOperator>(E);
19246 ExprResult LHS = Rebuild(CO->getLHS());
19247 if (LHS.isInvalid())
19248 return ExprError();
19249 ExprResult RHS = Rebuild(CO->getRHS());
19250 if (RHS.isInvalid())
19251 return ExprError();
19252 if (!LHS.isUsable() && !RHS.isUsable())
19253 return ExprEmpty();
19254 if (!LHS.isUsable())
19255 LHS = CO->getLHS();
19256 if (!RHS.isUsable())
19257 RHS = CO->getRHS();
19258 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
19259 CO->getCond(), LHS.get(), RHS.get());
19262 // [Clang extension]
19263 // -- If e has the form __extension__ e1...
19264 case Expr::UnaryOperatorClass: {
19265 auto *UO = cast<UnaryOperator>(E);
19266 if (UO->getOpcode() != UO_Extension)
19267 break;
19268 ExprResult Sub = Rebuild(UO->getSubExpr());
19269 if (!Sub.isUsable())
19270 return Sub;
19271 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
19272 Sub.get());
19275 // [Clang extension]
19276 // -- If e has the form _Generic(...), the set of potential results is the
19277 // union of the sets of potential results of the associated expressions.
19278 case Expr::GenericSelectionExprClass: {
19279 auto *GSE = cast<GenericSelectionExpr>(E);
19281 SmallVector<Expr *, 4> AssocExprs;
19282 bool AnyChanged = false;
19283 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
19284 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
19285 if (AssocExpr.isInvalid())
19286 return ExprError();
19287 if (AssocExpr.isUsable()) {
19288 AssocExprs.push_back(AssocExpr.get());
19289 AnyChanged = true;
19290 } else {
19291 AssocExprs.push_back(OrigAssocExpr);
19295 return AnyChanged ? S.CreateGenericSelectionExpr(
19296 GSE->getGenericLoc(), GSE->getDefaultLoc(),
19297 GSE->getRParenLoc(), GSE->getControllingExpr(),
19298 GSE->getAssocTypeSourceInfos(), AssocExprs)
19299 : ExprEmpty();
19302 // [Clang extension]
19303 // -- If e has the form __builtin_choose_expr(...), the set of potential
19304 // results is the union of the sets of potential results of the
19305 // second and third subexpressions.
19306 case Expr::ChooseExprClass: {
19307 auto *CE = cast<ChooseExpr>(E);
19309 ExprResult LHS = Rebuild(CE->getLHS());
19310 if (LHS.isInvalid())
19311 return ExprError();
19313 ExprResult RHS = Rebuild(CE->getLHS());
19314 if (RHS.isInvalid())
19315 return ExprError();
19317 if (!LHS.get() && !RHS.get())
19318 return ExprEmpty();
19319 if (!LHS.isUsable())
19320 LHS = CE->getLHS();
19321 if (!RHS.isUsable())
19322 RHS = CE->getRHS();
19324 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
19325 RHS.get(), CE->getRParenLoc());
19328 // Step through non-syntactic nodes.
19329 case Expr::ConstantExprClass: {
19330 auto *CE = cast<ConstantExpr>(E);
19331 ExprResult Sub = Rebuild(CE->getSubExpr());
19332 if (!Sub.isUsable())
19333 return Sub;
19334 return ConstantExpr::Create(S.Context, Sub.get());
19337 // We could mostly rely on the recursive rebuilding to rebuild implicit
19338 // casts, but not at the top level, so rebuild them here.
19339 case Expr::ImplicitCastExprClass: {
19340 auto *ICE = cast<ImplicitCastExpr>(E);
19341 // Only step through the narrow set of cast kinds we expect to encounter.
19342 // Anything else suggests we've left the region in which potential results
19343 // can be found.
19344 switch (ICE->getCastKind()) {
19345 case CK_NoOp:
19346 case CK_DerivedToBase:
19347 case CK_UncheckedDerivedToBase: {
19348 ExprResult Sub = Rebuild(ICE->getSubExpr());
19349 if (!Sub.isUsable())
19350 return Sub;
19351 CXXCastPath Path(ICE->path());
19352 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
19353 ICE->getValueKind(), &Path);
19356 default:
19357 break;
19359 break;
19362 default:
19363 break;
19366 // Can't traverse through this node. Nothing to do.
19367 return ExprEmpty();
19370 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
19371 // Check whether the operand is or contains an object of non-trivial C union
19372 // type.
19373 if (E->getType().isVolatileQualified() &&
19374 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
19375 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
19376 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
19377 Sema::NTCUC_LValueToRValueVolatile,
19378 NTCUK_Destruct|NTCUK_Copy);
19380 // C++2a [basic.def.odr]p4:
19381 // [...] an expression of non-volatile-qualified non-class type to which
19382 // the lvalue-to-rvalue conversion is applied [...]
19383 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
19384 return E;
19386 ExprResult Result =
19387 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
19388 if (Result.isInvalid())
19389 return ExprError();
19390 return Result.get() ? Result : E;
19393 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
19394 Res = CorrectDelayedTyposInExpr(Res);
19396 if (!Res.isUsable())
19397 return Res;
19399 // If a constant-expression is a reference to a variable where we delay
19400 // deciding whether it is an odr-use, just assume we will apply the
19401 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
19402 // (a non-type template argument), we have special handling anyway.
19403 return CheckLValueToRValueConversionOperand(Res.get());
19406 void Sema::CleanupVarDeclMarking() {
19407 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19408 // call.
19409 MaybeODRUseExprSet LocalMaybeODRUseExprs;
19410 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
19412 for (Expr *E : LocalMaybeODRUseExprs) {
19413 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
19414 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
19415 DRE->getLocation(), *this);
19416 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
19417 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
19418 *this);
19419 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
19420 for (VarDecl *VD : *FP)
19421 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
19422 } else {
19423 llvm_unreachable("Unexpected expression");
19427 assert(MaybeODRUseExprs.empty() &&
19428 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
19431 static void DoMarkVarDeclReferenced(
19432 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
19433 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19434 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
19435 isa<FunctionParmPackExpr>(E)) &&
19436 "Invalid Expr argument to DoMarkVarDeclReferenced");
19437 Var->setReferenced();
19439 if (Var->isInvalidDecl())
19440 return;
19442 auto *MSI = Var->getMemberSpecializationInfo();
19443 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
19444 : Var->getTemplateSpecializationKind();
19446 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19447 bool UsableInConstantExpr =
19448 Var->mightBeUsableInConstantExpressions(SemaRef.Context);
19450 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
19451 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
19454 // C++20 [expr.const]p12:
19455 // A variable [...] is needed for constant evaluation if it is [...] a
19456 // variable whose name appears as a potentially constant evaluated
19457 // expression that is either a contexpr variable or is of non-volatile
19458 // const-qualified integral type or of reference type
19459 bool NeededForConstantEvaluation =
19460 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
19462 bool NeedDefinition =
19463 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
19465 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
19466 "Can't instantiate a partial template specialization.");
19468 // If this might be a member specialization of a static data member, check
19469 // the specialization is visible. We already did the checks for variable
19470 // template specializations when we created them.
19471 if (NeedDefinition && TSK != TSK_Undeclared &&
19472 !isa<VarTemplateSpecializationDecl>(Var))
19473 SemaRef.checkSpecializationVisibility(Loc, Var);
19475 // Perform implicit instantiation of static data members, static data member
19476 // templates of class templates, and variable template specializations. Delay
19477 // instantiations of variable templates, except for those that could be used
19478 // in a constant expression.
19479 if (NeedDefinition && isTemplateInstantiation(TSK)) {
19480 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
19481 // instantiation declaration if a variable is usable in a constant
19482 // expression (among other cases).
19483 bool TryInstantiating =
19484 TSK == TSK_ImplicitInstantiation ||
19485 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
19487 if (TryInstantiating) {
19488 SourceLocation PointOfInstantiation =
19489 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
19490 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19491 if (FirstInstantiation) {
19492 PointOfInstantiation = Loc;
19493 if (MSI)
19494 MSI->setPointOfInstantiation(PointOfInstantiation);
19495 // FIXME: Notify listener.
19496 else
19497 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19500 if (UsableInConstantExpr) {
19501 // Do not defer instantiations of variables that could be used in a
19502 // constant expression.
19503 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
19504 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
19507 // Re-set the member to trigger a recomputation of the dependence bits
19508 // for the expression.
19509 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19510 DRE->setDecl(DRE->getDecl());
19511 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
19512 ME->setMemberDecl(ME->getMemberDecl());
19513 } else if (FirstInstantiation ||
19514 isa<VarTemplateSpecializationDecl>(Var)) {
19515 // FIXME: For a specialization of a variable template, we don't
19516 // distinguish between "declaration and type implicitly instantiated"
19517 // and "implicit instantiation of definition requested", so we have
19518 // no direct way to avoid enqueueing the pending instantiation
19519 // multiple times.
19520 SemaRef.PendingInstantiations
19521 .push_back(std::make_pair(Var, PointOfInstantiation));
19526 // C++2a [basic.def.odr]p4:
19527 // A variable x whose name appears as a potentially-evaluated expression e
19528 // is odr-used by e unless
19529 // -- x is a reference that is usable in constant expressions
19530 // -- x is a variable of non-reference type that is usable in constant
19531 // expressions and has no mutable subobjects [FIXME], and e is an
19532 // element of the set of potential results of an expression of
19533 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19534 // conversion is applied
19535 // -- x is a variable of non-reference type, and e is an element of the set
19536 // of potential results of a discarded-value expression to which the
19537 // lvalue-to-rvalue conversion is not applied [FIXME]
19539 // We check the first part of the second bullet here, and
19540 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
19541 // FIXME: To get the third bullet right, we need to delay this even for
19542 // variables that are not usable in constant expressions.
19544 // If we already know this isn't an odr-use, there's nothing more to do.
19545 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19546 if (DRE->isNonOdrUse())
19547 return;
19548 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
19549 if (ME->isNonOdrUse())
19550 return;
19552 switch (OdrUse) {
19553 case OdrUseContext::None:
19554 assert((!E || isa<FunctionParmPackExpr>(E)) &&
19555 "missing non-odr-use marking for unevaluated decl ref");
19556 break;
19558 case OdrUseContext::FormallyOdrUsed:
19559 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
19560 // behavior.
19561 break;
19563 case OdrUseContext::Used:
19564 // If we might later find that this expression isn't actually an odr-use,
19565 // delay the marking.
19566 if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
19567 SemaRef.MaybeODRUseExprs.insert(E);
19568 else
19569 MarkVarDeclODRUsed(Var, Loc, SemaRef);
19570 break;
19572 case OdrUseContext::Dependent:
19573 // If this is a dependent context, we don't need to mark variables as
19574 // odr-used, but we may still need to track them for lambda capture.
19575 // FIXME: Do we also need to do this inside dependent typeid expressions
19576 // (which are modeled as unevaluated at this point)?
19577 const bool RefersToEnclosingScope =
19578 (SemaRef.CurContext != Var->getDeclContext() &&
19579 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
19580 if (RefersToEnclosingScope) {
19581 LambdaScopeInfo *const LSI =
19582 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19583 if (LSI && (!LSI->CallOperator ||
19584 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
19585 // If a variable could potentially be odr-used, defer marking it so
19586 // until we finish analyzing the full expression for any
19587 // lvalue-to-rvalue
19588 // or discarded value conversions that would obviate odr-use.
19589 // Add it to the list of potential captures that will be analyzed
19590 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19591 // unless the variable is a reference that was initialized by a constant
19592 // expression (this will never need to be captured or odr-used).
19594 // FIXME: We can simplify this a lot after implementing P0588R1.
19595 assert(E && "Capture variable should be used in an expression.");
19596 if (!Var->getType()->isReferenceType() ||
19597 !Var->isUsableInConstantExpressions(SemaRef.Context))
19598 LSI->addPotentialCapture(E->IgnoreParens());
19601 break;
19605 static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc,
19606 BindingDecl *BD) {
19607 BD->setReferenced();
19609 if (BD->isInvalidDecl())
19610 return;
19612 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19613 if (OdrUse == OdrUseContext::Used) {
19614 QualType CaptureType, DeclRefType;
19615 SemaRef.tryCaptureVariable(BD, Loc, Sema::TryCapture_Implicit,
19616 /*EllipsisLoc*/ SourceLocation(),
19617 /*BuildAndDiagnose*/ true, CaptureType,
19618 DeclRefType,
19619 /*FunctionScopeIndexToStopAt*/ nullptr);
19623 /// Mark a variable referenced, and check whether it is odr-used
19624 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
19625 /// used directly for normal expressions referring to VarDecl.
19626 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
19627 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
19630 static void
19631 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
19632 bool MightBeOdrUse,
19633 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19634 if (SemaRef.isInOpenMPDeclareTargetContext())
19635 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
19637 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
19638 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
19639 return;
19642 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
19643 DoMarkBindingDeclReferenced(SemaRef, Loc, Decl);
19644 return;
19647 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
19649 // If this is a call to a method via a cast, also mark the method in the
19650 // derived class used in case codegen can devirtualize the call.
19651 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
19652 if (!ME)
19653 return;
19654 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
19655 if (!MD)
19656 return;
19657 // Only attempt to devirtualize if this is truly a virtual call.
19658 bool IsVirtualCall = MD->isVirtual() &&
19659 ME->performsVirtualDispatch(SemaRef.getLangOpts());
19660 if (!IsVirtualCall)
19661 return;
19663 // If it's possible to devirtualize the call, mark the called function
19664 // referenced.
19665 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
19666 ME->getBase(), SemaRef.getLangOpts().AppleKext);
19667 if (DM)
19668 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
19671 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
19673 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be
19674 /// handled with care if the DeclRefExpr is not newly-created.
19675 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
19676 // TODO: update this with DR# once a defect report is filed.
19677 // C++11 defect. The address of a pure member should not be an ODR use, even
19678 // if it's a qualified reference.
19679 bool OdrUse = true;
19680 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
19681 if (Method->isVirtual() &&
19682 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
19683 OdrUse = false;
19685 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
19686 if (!isUnevaluatedContext() && !isConstantEvaluated() &&
19687 !isImmediateFunctionContext() && FD->isConsteval() &&
19688 !RebuildingImmediateInvocation && !FD->isDependentContext())
19689 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
19690 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
19691 RefsMinusAssignments);
19694 /// Perform reference-marking and odr-use handling for a MemberExpr.
19695 void Sema::MarkMemberReferenced(MemberExpr *E) {
19696 // C++11 [basic.def.odr]p2:
19697 // A non-overloaded function whose name appears as a potentially-evaluated
19698 // expression or a member of a set of candidate functions, if selected by
19699 // overload resolution when referred to from a potentially-evaluated
19700 // expression, is odr-used, unless it is a pure virtual function and its
19701 // name is not explicitly qualified.
19702 bool MightBeOdrUse = true;
19703 if (E->performsVirtualDispatch(getLangOpts())) {
19704 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
19705 if (Method->isPure())
19706 MightBeOdrUse = false;
19708 SourceLocation Loc =
19709 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
19710 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
19711 RefsMinusAssignments);
19714 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
19715 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
19716 for (VarDecl *VD : *E)
19717 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
19718 RefsMinusAssignments);
19721 /// Perform marking for a reference to an arbitrary declaration. It
19722 /// marks the declaration referenced, and performs odr-use checking for
19723 /// functions and variables. This method should not be used when building a
19724 /// normal expression which refers to a variable.
19725 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
19726 bool MightBeOdrUse) {
19727 if (MightBeOdrUse) {
19728 if (auto *VD = dyn_cast<VarDecl>(D)) {
19729 MarkVariableReferenced(Loc, VD);
19730 return;
19733 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
19734 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
19735 return;
19737 D->setReferenced();
19740 namespace {
19741 // Mark all of the declarations used by a type as referenced.
19742 // FIXME: Not fully implemented yet! We need to have a better understanding
19743 // of when we're entering a context we should not recurse into.
19744 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
19745 // TreeTransforms rebuilding the type in a new context. Rather than
19746 // duplicating the TreeTransform logic, we should consider reusing it here.
19747 // Currently that causes problems when rebuilding LambdaExprs.
19748 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
19749 Sema &S;
19750 SourceLocation Loc;
19752 public:
19753 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
19755 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
19757 bool TraverseTemplateArgument(const TemplateArgument &Arg);
19761 bool MarkReferencedDecls::TraverseTemplateArgument(
19762 const TemplateArgument &Arg) {
19764 // A non-type template argument is a constant-evaluated context.
19765 EnterExpressionEvaluationContext Evaluated(
19766 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
19767 if (Arg.getKind() == TemplateArgument::Declaration) {
19768 if (Decl *D = Arg.getAsDecl())
19769 S.MarkAnyDeclReferenced(Loc, D, true);
19770 } else if (Arg.getKind() == TemplateArgument::Expression) {
19771 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
19775 return Inherited::TraverseTemplateArgument(Arg);
19778 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
19779 MarkReferencedDecls Marker(*this, Loc);
19780 Marker.TraverseType(T);
19783 namespace {
19784 /// Helper class that marks all of the declarations referenced by
19785 /// potentially-evaluated subexpressions as "referenced".
19786 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
19787 public:
19788 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
19789 bool SkipLocalVariables;
19790 ArrayRef<const Expr *> StopAt;
19792 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
19793 ArrayRef<const Expr *> StopAt)
19794 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
19796 void visitUsedDecl(SourceLocation Loc, Decl *D) {
19797 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
19800 void Visit(Expr *E) {
19801 if (llvm::is_contained(StopAt, E))
19802 return;
19803 Inherited::Visit(E);
19806 void VisitConstantExpr(ConstantExpr *E) {
19807 // Don't mark declarations within a ConstantExpression, as this expression
19808 // will be evaluated and folded to a value.
19811 void VisitDeclRefExpr(DeclRefExpr *E) {
19812 // If we were asked not to visit local variables, don't.
19813 if (SkipLocalVariables) {
19814 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
19815 if (VD->hasLocalStorage())
19816 return;
19819 // FIXME: This can trigger the instantiation of the initializer of a
19820 // variable, which can cause the expression to become value-dependent
19821 // or error-dependent. Do we need to propagate the new dependence bits?
19822 S.MarkDeclRefReferenced(E);
19825 void VisitMemberExpr(MemberExpr *E) {
19826 S.MarkMemberReferenced(E);
19827 Visit(E->getBase());
19830 } // namespace
19832 /// Mark any declarations that appear within this expression or any
19833 /// potentially-evaluated subexpressions as "referenced".
19835 /// \param SkipLocalVariables If true, don't mark local variables as
19836 /// 'referenced'.
19837 /// \param StopAt Subexpressions that we shouldn't recurse into.
19838 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
19839 bool SkipLocalVariables,
19840 ArrayRef<const Expr*> StopAt) {
19841 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
19844 /// Emit a diagnostic when statements are reachable.
19845 /// FIXME: check for reachability even in expressions for which we don't build a
19846 /// CFG (eg, in the initializer of a global or in a constant expression).
19847 /// For example,
19848 /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
19849 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
19850 const PartialDiagnostic &PD) {
19851 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
19852 if (!FunctionScopes.empty())
19853 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
19854 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
19855 return true;
19858 // The initializer of a constexpr variable or of the first declaration of a
19859 // static data member is not syntactically a constant evaluated constant,
19860 // but nonetheless is always required to be a constant expression, so we
19861 // can skip diagnosing.
19862 // FIXME: Using the mangling context here is a hack.
19863 if (auto *VD = dyn_cast_or_null<VarDecl>(
19864 ExprEvalContexts.back().ManglingContextDecl)) {
19865 if (VD->isConstexpr() ||
19866 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
19867 return false;
19868 // FIXME: For any other kind of variable, we should build a CFG for its
19869 // initializer and check whether the context in question is reachable.
19872 Diag(Loc, PD);
19873 return true;
19876 /// Emit a diagnostic that describes an effect on the run-time behavior
19877 /// of the program being compiled.
19879 /// This routine emits the given diagnostic when the code currently being
19880 /// type-checked is "potentially evaluated", meaning that there is a
19881 /// possibility that the code will actually be executable. Code in sizeof()
19882 /// expressions, code used only during overload resolution, etc., are not
19883 /// potentially evaluated. This routine will suppress such diagnostics or,
19884 /// in the absolutely nutty case of potentially potentially evaluated
19885 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
19886 /// later.
19888 /// This routine should be used for all diagnostics that describe the run-time
19889 /// behavior of a program, such as passing a non-POD value through an ellipsis.
19890 /// Failure to do so will likely result in spurious diagnostics or failures
19891 /// during overload resolution or within sizeof/alignof/typeof/typeid.
19892 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
19893 const PartialDiagnostic &PD) {
19895 if (ExprEvalContexts.back().isDiscardedStatementContext())
19896 return false;
19898 switch (ExprEvalContexts.back().Context) {
19899 case ExpressionEvaluationContext::Unevaluated:
19900 case ExpressionEvaluationContext::UnevaluatedList:
19901 case ExpressionEvaluationContext::UnevaluatedAbstract:
19902 case ExpressionEvaluationContext::DiscardedStatement:
19903 // The argument will never be evaluated, so don't complain.
19904 break;
19906 case ExpressionEvaluationContext::ConstantEvaluated:
19907 case ExpressionEvaluationContext::ImmediateFunctionContext:
19908 // Relevant diagnostics should be produced by constant evaluation.
19909 break;
19911 case ExpressionEvaluationContext::PotentiallyEvaluated:
19912 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
19913 return DiagIfReachable(Loc, Stmts, PD);
19916 return false;
19919 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
19920 const PartialDiagnostic &PD) {
19921 return DiagRuntimeBehavior(
19922 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
19925 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
19926 CallExpr *CE, FunctionDecl *FD) {
19927 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
19928 return false;
19930 // If we're inside a decltype's expression, don't check for a valid return
19931 // type or construct temporaries until we know whether this is the last call.
19932 if (ExprEvalContexts.back().ExprContext ==
19933 ExpressionEvaluationContextRecord::EK_Decltype) {
19934 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
19935 return false;
19938 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
19939 FunctionDecl *FD;
19940 CallExpr *CE;
19942 public:
19943 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
19944 : FD(FD), CE(CE) { }
19946 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
19947 if (!FD) {
19948 S.Diag(Loc, diag::err_call_incomplete_return)
19949 << T << CE->getSourceRange();
19950 return;
19953 S.Diag(Loc, diag::err_call_function_incomplete_return)
19954 << CE->getSourceRange() << FD << T;
19955 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
19956 << FD->getDeclName();
19958 } Diagnoser(FD, CE);
19960 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
19961 return true;
19963 return false;
19966 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
19967 // will prevent this condition from triggering, which is what we want.
19968 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
19969 SourceLocation Loc;
19971 unsigned diagnostic = diag::warn_condition_is_assignment;
19972 bool IsOrAssign = false;
19974 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
19975 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
19976 return;
19978 IsOrAssign = Op->getOpcode() == BO_OrAssign;
19980 // Greylist some idioms by putting them into a warning subcategory.
19981 if (ObjCMessageExpr *ME
19982 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
19983 Selector Sel = ME->getSelector();
19985 // self = [<foo> init...]
19986 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
19987 diagnostic = diag::warn_condition_is_idiomatic_assignment;
19989 // <foo> = [<bar> nextObject]
19990 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
19991 diagnostic = diag::warn_condition_is_idiomatic_assignment;
19994 Loc = Op->getOperatorLoc();
19995 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
19996 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
19997 return;
19999 IsOrAssign = Op->getOperator() == OO_PipeEqual;
20000 Loc = Op->getOperatorLoc();
20001 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
20002 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
20003 else {
20004 // Not an assignment.
20005 return;
20008 Diag(Loc, diagnostic) << E->getSourceRange();
20010 SourceLocation Open = E->getBeginLoc();
20011 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
20012 Diag(Loc, diag::note_condition_assign_silence)
20013 << FixItHint::CreateInsertion(Open, "(")
20014 << FixItHint::CreateInsertion(Close, ")");
20016 if (IsOrAssign)
20017 Diag(Loc, diag::note_condition_or_assign_to_comparison)
20018 << FixItHint::CreateReplacement(Loc, "!=");
20019 else
20020 Diag(Loc, diag::note_condition_assign_to_comparison)
20021 << FixItHint::CreateReplacement(Loc, "==");
20024 /// Redundant parentheses over an equality comparison can indicate
20025 /// that the user intended an assignment used as condition.
20026 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
20027 // Don't warn if the parens came from a macro.
20028 SourceLocation parenLoc = ParenE->getBeginLoc();
20029 if (parenLoc.isInvalid() || parenLoc.isMacroID())
20030 return;
20031 // Don't warn for dependent expressions.
20032 if (ParenE->isTypeDependent())
20033 return;
20035 Expr *E = ParenE->IgnoreParens();
20037 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
20038 if (opE->getOpcode() == BO_EQ &&
20039 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
20040 == Expr::MLV_Valid) {
20041 SourceLocation Loc = opE->getOperatorLoc();
20043 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
20044 SourceRange ParenERange = ParenE->getSourceRange();
20045 Diag(Loc, diag::note_equality_comparison_silence)
20046 << FixItHint::CreateRemoval(ParenERange.getBegin())
20047 << FixItHint::CreateRemoval(ParenERange.getEnd());
20048 Diag(Loc, diag::note_equality_comparison_to_assign)
20049 << FixItHint::CreateReplacement(Loc, "=");
20053 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
20054 bool IsConstexpr) {
20055 DiagnoseAssignmentAsCondition(E);
20056 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
20057 DiagnoseEqualityWithExtraParens(parenE);
20059 ExprResult result = CheckPlaceholderExpr(E);
20060 if (result.isInvalid()) return ExprError();
20061 E = result.get();
20063 if (!E->isTypeDependent()) {
20064 if (getLangOpts().CPlusPlus)
20065 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
20067 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
20068 if (ERes.isInvalid())
20069 return ExprError();
20070 E = ERes.get();
20072 QualType T = E->getType();
20073 if (!T->isScalarType()) { // C99 6.8.4.1p1
20074 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
20075 << T << E->getSourceRange();
20076 return ExprError();
20078 CheckBoolLikeConversion(E, Loc);
20081 return E;
20084 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
20085 Expr *SubExpr, ConditionKind CK,
20086 bool MissingOK) {
20087 // MissingOK indicates whether having no condition expression is valid
20088 // (for loop) or invalid (e.g. while loop).
20089 if (!SubExpr)
20090 return MissingOK ? ConditionResult() : ConditionError();
20092 ExprResult Cond;
20093 switch (CK) {
20094 case ConditionKind::Boolean:
20095 Cond = CheckBooleanCondition(Loc, SubExpr);
20096 break;
20098 case ConditionKind::ConstexprIf:
20099 Cond = CheckBooleanCondition(Loc, SubExpr, true);
20100 break;
20102 case ConditionKind::Switch:
20103 Cond = CheckSwitchCondition(Loc, SubExpr);
20104 break;
20106 if (Cond.isInvalid()) {
20107 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
20108 {SubExpr}, PreferredConditionType(CK));
20109 if (!Cond.get())
20110 return ConditionError();
20112 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
20113 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
20114 if (!FullExpr.get())
20115 return ConditionError();
20117 return ConditionResult(*this, nullptr, FullExpr,
20118 CK == ConditionKind::ConstexprIf);
20121 namespace {
20122 /// A visitor for rebuilding a call to an __unknown_any expression
20123 /// to have an appropriate type.
20124 struct RebuildUnknownAnyFunction
20125 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
20127 Sema &S;
20129 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
20131 ExprResult VisitStmt(Stmt *S) {
20132 llvm_unreachable("unexpected statement!");
20135 ExprResult VisitExpr(Expr *E) {
20136 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
20137 << E->getSourceRange();
20138 return ExprError();
20141 /// Rebuild an expression which simply semantically wraps another
20142 /// expression which it shares the type and value kind of.
20143 template <class T> ExprResult rebuildSugarExpr(T *E) {
20144 ExprResult SubResult = Visit(E->getSubExpr());
20145 if (SubResult.isInvalid()) return ExprError();
20147 Expr *SubExpr = SubResult.get();
20148 E->setSubExpr(SubExpr);
20149 E->setType(SubExpr->getType());
20150 E->setValueKind(SubExpr->getValueKind());
20151 assert(E->getObjectKind() == OK_Ordinary);
20152 return E;
20155 ExprResult VisitParenExpr(ParenExpr *E) {
20156 return rebuildSugarExpr(E);
20159 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20160 return rebuildSugarExpr(E);
20163 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20164 ExprResult SubResult = Visit(E->getSubExpr());
20165 if (SubResult.isInvalid()) return ExprError();
20167 Expr *SubExpr = SubResult.get();
20168 E->setSubExpr(SubExpr);
20169 E->setType(S.Context.getPointerType(SubExpr->getType()));
20170 assert(E->isPRValue());
20171 assert(E->getObjectKind() == OK_Ordinary);
20172 return E;
20175 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
20176 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
20178 E->setType(VD->getType());
20180 assert(E->isPRValue());
20181 if (S.getLangOpts().CPlusPlus &&
20182 !(isa<CXXMethodDecl>(VD) &&
20183 cast<CXXMethodDecl>(VD)->isInstance()))
20184 E->setValueKind(VK_LValue);
20186 return E;
20189 ExprResult VisitMemberExpr(MemberExpr *E) {
20190 return resolveDecl(E, E->getMemberDecl());
20193 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20194 return resolveDecl(E, E->getDecl());
20199 /// Given a function expression of unknown-any type, try to rebuild it
20200 /// to have a function type.
20201 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
20202 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20203 if (Result.isInvalid()) return ExprError();
20204 return S.DefaultFunctionArrayConversion(Result.get());
20207 namespace {
20208 /// A visitor for rebuilding an expression of type __unknown_anytype
20209 /// into one which resolves the type directly on the referring
20210 /// expression. Strict preservation of the original source
20211 /// structure is not a goal.
20212 struct RebuildUnknownAnyExpr
20213 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
20215 Sema &S;
20217 /// The current destination type.
20218 QualType DestType;
20220 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
20221 : S(S), DestType(CastType) {}
20223 ExprResult VisitStmt(Stmt *S) {
20224 llvm_unreachable("unexpected statement!");
20227 ExprResult VisitExpr(Expr *E) {
20228 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20229 << E->getSourceRange();
20230 return ExprError();
20233 ExprResult VisitCallExpr(CallExpr *E);
20234 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
20236 /// Rebuild an expression which simply semantically wraps another
20237 /// expression which it shares the type and value kind of.
20238 template <class T> ExprResult rebuildSugarExpr(T *E) {
20239 ExprResult SubResult = Visit(E->getSubExpr());
20240 if (SubResult.isInvalid()) return ExprError();
20241 Expr *SubExpr = SubResult.get();
20242 E->setSubExpr(SubExpr);
20243 E->setType(SubExpr->getType());
20244 E->setValueKind(SubExpr->getValueKind());
20245 assert(E->getObjectKind() == OK_Ordinary);
20246 return E;
20249 ExprResult VisitParenExpr(ParenExpr *E) {
20250 return rebuildSugarExpr(E);
20253 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20254 return rebuildSugarExpr(E);
20257 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20258 const PointerType *Ptr = DestType->getAs<PointerType>();
20259 if (!Ptr) {
20260 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
20261 << E->getSourceRange();
20262 return ExprError();
20265 if (isa<CallExpr>(E->getSubExpr())) {
20266 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
20267 << E->getSourceRange();
20268 return ExprError();
20271 assert(E->isPRValue());
20272 assert(E->getObjectKind() == OK_Ordinary);
20273 E->setType(DestType);
20275 // Build the sub-expression as if it were an object of the pointee type.
20276 DestType = Ptr->getPointeeType();
20277 ExprResult SubResult = Visit(E->getSubExpr());
20278 if (SubResult.isInvalid()) return ExprError();
20279 E->setSubExpr(SubResult.get());
20280 return E;
20283 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
20285 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
20287 ExprResult VisitMemberExpr(MemberExpr *E) {
20288 return resolveDecl(E, E->getMemberDecl());
20291 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20292 return resolveDecl(E, E->getDecl());
20297 /// Rebuilds a call expression which yielded __unknown_anytype.
20298 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
20299 Expr *CalleeExpr = E->getCallee();
20301 enum FnKind {
20302 FK_MemberFunction,
20303 FK_FunctionPointer,
20304 FK_BlockPointer
20307 FnKind Kind;
20308 QualType CalleeType = CalleeExpr->getType();
20309 if (CalleeType == S.Context.BoundMemberTy) {
20310 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
20311 Kind = FK_MemberFunction;
20312 CalleeType = Expr::findBoundMemberType(CalleeExpr);
20313 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
20314 CalleeType = Ptr->getPointeeType();
20315 Kind = FK_FunctionPointer;
20316 } else {
20317 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
20318 Kind = FK_BlockPointer;
20320 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
20322 // Verify that this is a legal result type of a function.
20323 if (DestType->isArrayType() || DestType->isFunctionType()) {
20324 unsigned diagID = diag::err_func_returning_array_function;
20325 if (Kind == FK_BlockPointer)
20326 diagID = diag::err_block_returning_array_function;
20328 S.Diag(E->getExprLoc(), diagID)
20329 << DestType->isFunctionType() << DestType;
20330 return ExprError();
20333 // Otherwise, go ahead and set DestType as the call's result.
20334 E->setType(DestType.getNonLValueExprType(S.Context));
20335 E->setValueKind(Expr::getValueKindForType(DestType));
20336 assert(E->getObjectKind() == OK_Ordinary);
20338 // Rebuild the function type, replacing the result type with DestType.
20339 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
20340 if (Proto) {
20341 // __unknown_anytype(...) is a special case used by the debugger when
20342 // it has no idea what a function's signature is.
20344 // We want to build this call essentially under the K&R
20345 // unprototyped rules, but making a FunctionNoProtoType in C++
20346 // would foul up all sorts of assumptions. However, we cannot
20347 // simply pass all arguments as variadic arguments, nor can we
20348 // portably just call the function under a non-variadic type; see
20349 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
20350 // However, it turns out that in practice it is generally safe to
20351 // call a function declared as "A foo(B,C,D);" under the prototype
20352 // "A foo(B,C,D,...);". The only known exception is with the
20353 // Windows ABI, where any variadic function is implicitly cdecl
20354 // regardless of its normal CC. Therefore we change the parameter
20355 // types to match the types of the arguments.
20357 // This is a hack, but it is far superior to moving the
20358 // corresponding target-specific code from IR-gen to Sema/AST.
20360 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
20361 SmallVector<QualType, 8> ArgTypes;
20362 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
20363 ArgTypes.reserve(E->getNumArgs());
20364 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
20365 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
20367 ParamTypes = ArgTypes;
20369 DestType = S.Context.getFunctionType(DestType, ParamTypes,
20370 Proto->getExtProtoInfo());
20371 } else {
20372 DestType = S.Context.getFunctionNoProtoType(DestType,
20373 FnType->getExtInfo());
20376 // Rebuild the appropriate pointer-to-function type.
20377 switch (Kind) {
20378 case FK_MemberFunction:
20379 // Nothing to do.
20380 break;
20382 case FK_FunctionPointer:
20383 DestType = S.Context.getPointerType(DestType);
20384 break;
20386 case FK_BlockPointer:
20387 DestType = S.Context.getBlockPointerType(DestType);
20388 break;
20391 // Finally, we can recurse.
20392 ExprResult CalleeResult = Visit(CalleeExpr);
20393 if (!CalleeResult.isUsable()) return ExprError();
20394 E->setCallee(CalleeResult.get());
20396 // Bind a temporary if necessary.
20397 return S.MaybeBindToTemporary(E);
20400 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
20401 // Verify that this is a legal result type of a call.
20402 if (DestType->isArrayType() || DestType->isFunctionType()) {
20403 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
20404 << DestType->isFunctionType() << DestType;
20405 return ExprError();
20408 // Rewrite the method result type if available.
20409 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
20410 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
20411 Method->setReturnType(DestType);
20414 // Change the type of the message.
20415 E->setType(DestType.getNonReferenceType());
20416 E->setValueKind(Expr::getValueKindForType(DestType));
20418 return S.MaybeBindToTemporary(E);
20421 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
20422 // The only case we should ever see here is a function-to-pointer decay.
20423 if (E->getCastKind() == CK_FunctionToPointerDecay) {
20424 assert(E->isPRValue());
20425 assert(E->getObjectKind() == OK_Ordinary);
20427 E->setType(DestType);
20429 // Rebuild the sub-expression as the pointee (function) type.
20430 DestType = DestType->castAs<PointerType>()->getPointeeType();
20432 ExprResult Result = Visit(E->getSubExpr());
20433 if (!Result.isUsable()) return ExprError();
20435 E->setSubExpr(Result.get());
20436 return E;
20437 } else if (E->getCastKind() == CK_LValueToRValue) {
20438 assert(E->isPRValue());
20439 assert(E->getObjectKind() == OK_Ordinary);
20441 assert(isa<BlockPointerType>(E->getType()));
20443 E->setType(DestType);
20445 // The sub-expression has to be a lvalue reference, so rebuild it as such.
20446 DestType = S.Context.getLValueReferenceType(DestType);
20448 ExprResult Result = Visit(E->getSubExpr());
20449 if (!Result.isUsable()) return ExprError();
20451 E->setSubExpr(Result.get());
20452 return E;
20453 } else {
20454 llvm_unreachable("Unhandled cast type!");
20458 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
20459 ExprValueKind ValueKind = VK_LValue;
20460 QualType Type = DestType;
20462 // We know how to make this work for certain kinds of decls:
20464 // - functions
20465 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
20466 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
20467 DestType = Ptr->getPointeeType();
20468 ExprResult Result = resolveDecl(E, VD);
20469 if (Result.isInvalid()) return ExprError();
20470 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
20471 VK_PRValue);
20474 if (!Type->isFunctionType()) {
20475 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
20476 << VD << E->getSourceRange();
20477 return ExprError();
20479 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
20480 // We must match the FunctionDecl's type to the hack introduced in
20481 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
20482 // type. See the lengthy commentary in that routine.
20483 QualType FDT = FD->getType();
20484 const FunctionType *FnType = FDT->castAs<FunctionType>();
20485 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
20486 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
20487 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
20488 SourceLocation Loc = FD->getLocation();
20489 FunctionDecl *NewFD = FunctionDecl::Create(
20490 S.Context, FD->getDeclContext(), Loc, Loc,
20491 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
20492 SC_None, S.getCurFPFeatures().isFPConstrained(),
20493 false /*isInlineSpecified*/, FD->hasPrototype(),
20494 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
20496 if (FD->getQualifier())
20497 NewFD->setQualifierInfo(FD->getQualifierLoc());
20499 SmallVector<ParmVarDecl*, 16> Params;
20500 for (const auto &AI : FT->param_types()) {
20501 ParmVarDecl *Param =
20502 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
20503 Param->setScopeInfo(0, Params.size());
20504 Params.push_back(Param);
20506 NewFD->setParams(Params);
20507 DRE->setDecl(NewFD);
20508 VD = DRE->getDecl();
20512 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
20513 if (MD->isInstance()) {
20514 ValueKind = VK_PRValue;
20515 Type = S.Context.BoundMemberTy;
20518 // Function references aren't l-values in C.
20519 if (!S.getLangOpts().CPlusPlus)
20520 ValueKind = VK_PRValue;
20522 // - variables
20523 } else if (isa<VarDecl>(VD)) {
20524 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
20525 Type = RefTy->getPointeeType();
20526 } else if (Type->isFunctionType()) {
20527 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
20528 << VD << E->getSourceRange();
20529 return ExprError();
20532 // - nothing else
20533 } else {
20534 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
20535 << VD << E->getSourceRange();
20536 return ExprError();
20539 // Modifying the declaration like this is friendly to IR-gen but
20540 // also really dangerous.
20541 VD->setType(DestType);
20542 E->setType(Type);
20543 E->setValueKind(ValueKind);
20544 return E;
20547 /// Check a cast of an unknown-any type. We intentionally only
20548 /// trigger this for C-style casts.
20549 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
20550 Expr *CastExpr, CastKind &CastKind,
20551 ExprValueKind &VK, CXXCastPath &Path) {
20552 // The type we're casting to must be either void or complete.
20553 if (!CastType->isVoidType() &&
20554 RequireCompleteType(TypeRange.getBegin(), CastType,
20555 diag::err_typecheck_cast_to_incomplete))
20556 return ExprError();
20558 // Rewrite the casted expression from scratch.
20559 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
20560 if (!result.isUsable()) return ExprError();
20562 CastExpr = result.get();
20563 VK = CastExpr->getValueKind();
20564 CastKind = CK_NoOp;
20566 return CastExpr;
20569 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
20570 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
20573 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
20574 Expr *arg, QualType &paramType) {
20575 // If the syntactic form of the argument is not an explicit cast of
20576 // any sort, just do default argument promotion.
20577 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
20578 if (!castArg) {
20579 ExprResult result = DefaultArgumentPromotion(arg);
20580 if (result.isInvalid()) return ExprError();
20581 paramType = result.get()->getType();
20582 return result;
20585 // Otherwise, use the type that was written in the explicit cast.
20586 assert(!arg->hasPlaceholderType());
20587 paramType = castArg->getTypeAsWritten();
20589 // Copy-initialize a parameter of that type.
20590 InitializedEntity entity =
20591 InitializedEntity::InitializeParameter(Context, paramType,
20592 /*consumed*/ false);
20593 return PerformCopyInitialization(entity, callLoc, arg);
20596 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
20597 Expr *orig = E;
20598 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
20599 while (true) {
20600 E = E->IgnoreParenImpCasts();
20601 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
20602 E = call->getCallee();
20603 diagID = diag::err_uncasted_call_of_unknown_any;
20604 } else {
20605 break;
20609 SourceLocation loc;
20610 NamedDecl *d;
20611 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
20612 loc = ref->getLocation();
20613 d = ref->getDecl();
20614 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
20615 loc = mem->getMemberLoc();
20616 d = mem->getMemberDecl();
20617 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
20618 diagID = diag::err_uncasted_call_of_unknown_any;
20619 loc = msg->getSelectorStartLoc();
20620 d = msg->getMethodDecl();
20621 if (!d) {
20622 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
20623 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
20624 << orig->getSourceRange();
20625 return ExprError();
20627 } else {
20628 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20629 << E->getSourceRange();
20630 return ExprError();
20633 S.Diag(loc, diagID) << d << orig->getSourceRange();
20635 // Never recoverable.
20636 return ExprError();
20639 /// Check for operands with placeholder types and complain if found.
20640 /// Returns ExprError() if there was an error and no recovery was possible.
20641 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
20642 if (!Context.isDependenceAllowed()) {
20643 // C cannot handle TypoExpr nodes on either side of a binop because it
20644 // doesn't handle dependent types properly, so make sure any TypoExprs have
20645 // been dealt with before checking the operands.
20646 ExprResult Result = CorrectDelayedTyposInExpr(E);
20647 if (!Result.isUsable()) return ExprError();
20648 E = Result.get();
20651 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
20652 if (!placeholderType) return E;
20654 switch (placeholderType->getKind()) {
20656 // Overloaded expressions.
20657 case BuiltinType::Overload: {
20658 // Try to resolve a single function template specialization.
20659 // This is obligatory.
20660 ExprResult Result = E;
20661 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
20662 return Result;
20664 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
20665 // leaves Result unchanged on failure.
20666 Result = E;
20667 if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
20668 return Result;
20670 // If that failed, try to recover with a call.
20671 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
20672 /*complain*/ true);
20673 return Result;
20676 // Bound member functions.
20677 case BuiltinType::BoundMember: {
20678 ExprResult result = E;
20679 const Expr *BME = E->IgnoreParens();
20680 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
20681 // Try to give a nicer diagnostic if it is a bound member that we recognize.
20682 if (isa<CXXPseudoDestructorExpr>(BME)) {
20683 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
20684 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
20685 if (ME->getMemberNameInfo().getName().getNameKind() ==
20686 DeclarationName::CXXDestructorName)
20687 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
20689 tryToRecoverWithCall(result, PD,
20690 /*complain*/ true);
20691 return result;
20694 // ARC unbridged casts.
20695 case BuiltinType::ARCUnbridgedCast: {
20696 Expr *realCast = stripARCUnbridgedCast(E);
20697 diagnoseARCUnbridgedCast(realCast);
20698 return realCast;
20701 // Expressions of unknown type.
20702 case BuiltinType::UnknownAny:
20703 return diagnoseUnknownAnyExpr(*this, E);
20705 // Pseudo-objects.
20706 case BuiltinType::PseudoObject:
20707 return checkPseudoObjectRValue(E);
20709 case BuiltinType::BuiltinFn: {
20710 // Accept __noop without parens by implicitly converting it to a call expr.
20711 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
20712 if (DRE) {
20713 auto *FD = cast<FunctionDecl>(DRE->getDecl());
20714 unsigned BuiltinID = FD->getBuiltinID();
20715 if (BuiltinID == Builtin::BI__noop) {
20716 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
20717 CK_BuiltinFnToFnPtr)
20718 .get();
20719 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
20720 VK_PRValue, SourceLocation(),
20721 FPOptionsOverride());
20724 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
20725 // Any use of these other than a direct call is ill-formed as of C++20,
20726 // because they are not addressable functions. In earlier language
20727 // modes, warn and force an instantiation of the real body.
20728 Diag(E->getBeginLoc(),
20729 getLangOpts().CPlusPlus20
20730 ? diag::err_use_of_unaddressable_function
20731 : diag::warn_cxx20_compat_use_of_unaddressable_function);
20732 if (FD->isImplicitlyInstantiable()) {
20733 // Require a definition here because a normal attempt at
20734 // instantiation for a builtin will be ignored, and we won't try
20735 // again later. We assume that the definition of the template
20736 // precedes this use.
20737 InstantiateFunctionDefinition(E->getBeginLoc(), FD,
20738 /*Recursive=*/false,
20739 /*DefinitionRequired=*/true,
20740 /*AtEndOfTU=*/false);
20742 // Produce a properly-typed reference to the function.
20743 CXXScopeSpec SS;
20744 SS.Adopt(DRE->getQualifierLoc());
20745 TemplateArgumentListInfo TemplateArgs;
20746 DRE->copyTemplateArgumentsInto(TemplateArgs);
20747 return BuildDeclRefExpr(
20748 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
20749 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
20750 DRE->getTemplateKeywordLoc(),
20751 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
20755 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
20756 return ExprError();
20759 case BuiltinType::IncompleteMatrixIdx:
20760 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
20761 ->getRowIdx()
20762 ->getBeginLoc(),
20763 diag::err_matrix_incomplete_index);
20764 return ExprError();
20766 // Expressions of unknown type.
20767 case BuiltinType::OMPArraySection:
20768 Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
20769 return ExprError();
20771 // Expressions of unknown type.
20772 case BuiltinType::OMPArrayShaping:
20773 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
20775 case BuiltinType::OMPIterator:
20776 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
20778 // Everything else should be impossible.
20779 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
20780 case BuiltinType::Id:
20781 #include "clang/Basic/OpenCLImageTypes.def"
20782 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
20783 case BuiltinType::Id:
20784 #include "clang/Basic/OpenCLExtensionTypes.def"
20785 #define SVE_TYPE(Name, Id, SingletonId) \
20786 case BuiltinType::Id:
20787 #include "clang/Basic/AArch64SVEACLETypes.def"
20788 #define PPC_VECTOR_TYPE(Name, Id, Size) \
20789 case BuiltinType::Id:
20790 #include "clang/Basic/PPCTypes.def"
20791 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
20792 #include "clang/Basic/RISCVVTypes.def"
20793 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
20794 #define PLACEHOLDER_TYPE(Id, SingletonId)
20795 #include "clang/AST/BuiltinTypes.def"
20796 break;
20799 llvm_unreachable("invalid placeholder type!");
20802 bool Sema::CheckCaseExpression(Expr *E) {
20803 if (E->isTypeDependent())
20804 return true;
20805 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
20806 return E->getType()->isIntegralOrEnumerationType();
20807 return false;
20810 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
20811 ExprResult
20812 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
20813 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
20814 "Unknown Objective-C Boolean value!");
20815 QualType BoolT = Context.ObjCBuiltinBoolTy;
20816 if (!Context.getBOOLDecl()) {
20817 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
20818 Sema::LookupOrdinaryName);
20819 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
20820 NamedDecl *ND = Result.getFoundDecl();
20821 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
20822 Context.setBOOLDecl(TD);
20825 if (Context.getBOOLDecl())
20826 BoolT = Context.getBOOLType();
20827 return new (Context)
20828 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
20831 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
20832 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
20833 SourceLocation RParen) {
20834 auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> {
20835 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
20836 return Spec.getPlatform() == Platform;
20838 // Transcribe the "ios" availability check to "maccatalyst" when compiling
20839 // for "maccatalyst" if "maccatalyst" is not specified.
20840 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
20841 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
20842 return Spec.getPlatform() == "ios";
20845 if (Spec == AvailSpecs.end())
20846 return None;
20847 return Spec->getVersion();
20850 VersionTuple Version;
20851 if (auto MaybeVersion =
20852 FindSpecVersion(Context.getTargetInfo().getPlatformName()))
20853 Version = *MaybeVersion;
20855 // The use of `@available` in the enclosing context should be analyzed to
20856 // warn when it's used inappropriately (i.e. not if(@available)).
20857 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
20858 Context->HasPotentialAvailabilityViolations = true;
20860 return new (Context)
20861 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
20864 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
20865 ArrayRef<Expr *> SubExprs, QualType T) {
20866 if (!Context.getLangOpts().RecoveryAST)
20867 return ExprError();
20869 if (isSFINAEContext())
20870 return ExprError();
20872 if (T.isNull() || T->isUndeducedType() ||
20873 !Context.getLangOpts().RecoveryASTType)
20874 // We don't know the concrete type, fallback to dependent type.
20875 T = Context.DependentTy;
20877 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);